How can you replace values in a NumPy array based on a condition using boolean indexing?

Quick Overview

Explain how to replace values in a NumPy array that meet a condition, both in place and as a new array. Tests boolean masks, combining conditions, and the casting, NaN and copy pitfalls that make conditional replacement go wrong.

How can you replace values in a NumPy array based on a condition using boolean indexing?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

How can you replace values in a NumPy array based on a condition using boolean indexing? ```hint Masks on both sides A comparison on an array gives an array of booleans. Think about what happens when that array is used inside the square brackets on the left of an assignment, and whether you want the original array changed. ``` ### What a Strong Answer Covers - How a boolean mask is built from a condition and used to assign to the selected positions - The difference between changing the array in place and building a new array with `np.where` - How to combine several conditions correctly - At least one pitfall, such as dtype casting on assignment, comparisons with `NaN`, or assigning through a copy ### Follow-up Questions - Why does `a[a > 0][0] = 99` leave `a` unchanged, while `a[a > 0] = 99` changes it? - What happens when you assign `2.7` or `np.nan` to masked positions of an integer array? - How would you map values into several categories at once without nesting `np.where` calls?

Overview: Explain how to replace values in a NumPy array that meet a condition, both in place and as a new array. Tests boolean masks, combining conditions, and the casting, NaN and copy pitfalls that make conditional replacement go wrong.

PracHub logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

How can you replace values in a NumPy array based on a condition using boolean indexing?

What a Strong Answer Covers Guidance

  • How a boolean mask is built from a condition and used to assign to the selected positions
  • The difference between changing the array in place and building a new array with np.where
  • How to combine several conditions correctly
  • At least one pitfall, such as dtype casting on assignment, comparisons with NaN , or assigning through a copy

Follow-up Questions Guidance

  • Why does a[a > 0][0] = 99 leave a unchanged, while a[a > 0] = 99 changes it?
  • What happens when you assign 2.7 or np.nan to masked positions of an integer array?
  • How would you map values into several categories at once without nesting np.where calls?