0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.where for Condition in NumPy: Simple Guide

Use np.where(condition, x, y) to select elements from x where the condition is true, and from y where it is false. It returns an array with elements chosen based on the condition.
๐Ÿ“

Syntax

The basic syntax of np.where is:

  • condition: A boolean array or expression to test each element.
  • x: Values to choose where condition is true.
  • y: Values to choose where condition is false.

If only condition is provided, it returns the indices where the condition is true.

python
np.where(condition, x, y)
๐Ÿ’ป

Example

This example shows how to use np.where to replace values in an array based on a condition. It replaces values greater than 5 with 10, and others with 0.

python
import numpy as np

arr = np.array([3, 7, 2, 9, 5])
result = np.where(arr > 5, 10, 0)
print(result)
Output
[ 0 10 0 10 0]
โš ๏ธ

Common Pitfalls

One common mistake is to use np.where without providing both x and y when you want to replace values. If you only provide the condition, it returns indices, not replaced values.

Also, ensure x and y have compatible shapes with the condition to avoid errors.

python
import numpy as np

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

# Wrong: expecting replaced values but only condition given
indices = np.where(arr > 2)
print(indices)  # This prints indices, not replaced array

# Right: provide x and y to get replaced values
replaced = np.where(arr > 2, 100, -100)
print(replaced)
Output
(array([2, 3]),) [100 100 -100 -100]
๐Ÿ“Š

Quick Reference

ParameterDescription
conditionBoolean array or expression to test each element
xValue or array chosen where condition is True
yValue or array chosen where condition is False
ReturnArray with elements from x or y based on condition
โœ…

Key Takeaways

Use np.where(condition, x, y) to select elements based on a condition.
If only condition is given, np.where returns indices where condition is true.
Ensure x and y have compatible shapes with the condition to avoid errors.
np.where is useful for quick element-wise replacement in arrays.
Remember np.where returns a new array; it does not modify the original.