0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use numpy.where: Simple Guide with Examples

Use numpy.where(condition, x, y) to select elements from x or y depending on the condition. If only condition is given, it returns the indices where the condition is true.
๐Ÿ“

Syntax

The numpy.where function has two main forms:

  • numpy.where(condition): Returns indices where condition is true.
  • numpy.where(condition, x, y): Returns elements from x where condition is true, else from y.

Parameters:

  • condition: A boolean array or expression.
  • x: Array or value to choose where condition is true.
  • y: Array or value to choose where condition is false.
python
import numpy as np

# Form 1: Get indices where condition is true
indices = np.where(np.array([1, 2, 3, 4]) > 2)

# Form 2: Choose elements based on condition
result = np.where(np.array([1, 2, 3, 4]) > 2, 'Yes', 'No')
๐Ÿ’ป

Example

This example shows how to find indices where values are greater than 3 and how to replace values conditionally.

python
import numpy as np

arr = np.array([1, 4, 2, 5, 3])

# Find indices where values > 3
indices = np.where(arr > 3)

# Replace values > 3 with 10, else keep original
new_arr = np.where(arr > 3, 10, arr)

print("Indices where arr > 3:", indices)
print("Array after replacement:", new_arr)
Output
Indices where arr > 3: (array([1, 3]),) Array after replacement: [ 1 10 2 10 3]
โš ๏ธ

Common Pitfalls

1. Forgetting that np.where(condition) returns a tuple of arrays for each dimension, not a flat list. You often need to use indices[0] for 1D arrays.

2. Mixing shapes of x and y arrays causes errors. Both must be broadcastable to the same shape.

3. Using np.where without x and y when you want to replace values. This only returns indices, not replaced values.

python
import numpy as np

arr = np.array([1, 2, 3, 4])

# Wrong: expecting replaced array but only get indices
wrong = np.where(arr > 2)
print("Wrong output:", wrong)

# Right: provide x and y to replace values
right = np.where(arr > 2, 100, arr)
print("Right output:", right)
Output
Wrong output: (array([2, 3]),) Right output: [ 1 2 100 100]
๐Ÿ“Š

Quick Reference

UsageDescriptionExample
np.where(condition)Returns indices where condition is truenp.where(arr > 3)
np.where(condition, x, y)Select elements from x or y based on conditionnp.where(arr > 3, 10, arr)
Output of np.where(condition)Tuple of arrays for each dimension(array([indices]),)
x and y shapesMust be broadcastable to same shapenp.where(cond, x_array, y_array)
โœ…

Key Takeaways

Use np.where(condition) to get indices where the condition is true.
Use np.where(condition, x, y) to select elements from x or y based on the condition.
Remember np.where(condition) returns a tuple of arrays, not a flat list.
Ensure x and y have compatible shapes when using the three-argument form.
Without x and y, np.where only returns indices, not replaced values.