numpy.where() in Python (original) (raw)

Last Updated : 30 Sep, 2025

numpy.where() is used for conditional selection and replacement in NumPy arrays. It can be used to:

In this example, np.where() is used with only a condition to get the indices where elements are greater than 20.

Python `

import numpy as np arr = np.array([10, 15, 20, 25, 30]) result = np.where(arr > 20) print(result)

`

**Explanation:

Syntax:

numpy.where(condition[, x, y])

**Parameters:

**Return value:

Uses of numpy.where()

1. Find indices that satisfy a condition

In this example, numpy.where() checks where the condition arr % 2 == 0 is true and returns the indices.

Python `

import numpy as np arr = np.array([2, 7, 8, 3, 10]) idx = np.where(arr % 2 == 0)
print(idx) print("Even elements:", arr[idx])

`

Output

(array([0, 2, 4]),) Even elements: [ 2 8 10]

**Explanation:

2. Binary replacement with scalars (x and y)

By providing x and y as arguments, you can use numpy.where() to return different values depending on whether condition is true or false.

Here, numpy.where() function checks the condition arr > 20.

Python `

import numpy as np arr = np.array([10, 15, 20, 25, 30]) result = np.where(arr > 20, 1, 0) print(result)

`

**Explanation:

3. Pick from two arrays elementwise

In this example, for elements where condition arr1 > 20 is true, corresponding element from arr1 is chosen. Otherwise, element from arr2 is selected.

Python `

import numpy as np arr1 = np.array([10, 15, 20, 25, 30]) arr2 = np.array([100, 150, 200, 250, 300]) result = np.where(arr1 > 20, arr1, arr2) print(result)

`

Output

[100 150 200 25 30]

**Explanation:

4. Replace negatives with zero

This example replaces negative numbers in a 2-D array with 0.

Python `

import numpy as np mat = np.array([[ 5, -2, 3], [-1, 4, -6]]) result = np.where(mat < 0, 0, mat) print(result)

`

**Explanation: