NumPy Tutorial NumPy Statistics NumPy References

NumPy - where() function



The NumPy where() function returns elements chosen from x or y depending on condition. When only condition is provided, the function returns the indices of elements of the given array which satisfies the condition.

Syntax

numpy.where(condition, x, y)

Parameters

condition Required. Specify array_like, bool. Where True, yield x, otherwise yield y.
x, y Optional. Specify array_like values from which to choose. x, y and condition need to be broadcastable to some shape.

Return Value

Returns an array with elements from x where condition is True, and elements from y elsewhere.

Example:

In the example below, where() function is used to replace all negative elements with 0 from an array.

import numpy as np

x = np.arange(-2, 5)

#replacing all negative elements with 0
y = np.where(x > 0, x, 0)

#displaying the content of x and y
print("x contains:", x)
print("y contains:", y)

The output of the above code will be:

x contains: [-2 -1  0  1  2  3  4]
y contains: [0 0 0 1 2 3 4]

Example:

In this example, where() function is used to choose elements from two array based on a given condition.

import numpy as np

x = np.asarray([[10, 20], [30, 40]])
y = np.asarray([[15, 15], [25, 25]])

#applying where condition
z = np.where(x > y, x, y)

#displaying the content of x, y and z
print("x =")
print(x)
print("\ny =")
print(y)
print("\nz =")
print(z)

The output of the above code will be:

x =
[[10 20]
 [30 40]]

y =
[[15 15]
 [25 25]]

z =
[[15 20]
 [30 40]]

Example:

When only condition is provided, the function returns the indices of elements of the given array which satisfies the condition. Consider the following example:

import numpy as np

x = np.asarray([10, 20, 30, 40, 50, 60])

#applying where condition
y = np.where(x > 35)

#displaying the result
print("x =", x)
print("y =", y)
print("x[y] =", x[y])

The output of the above code will be:

x = [10 20 30 40 50 60]
y = (array([3, 4, 5]),)
x[y] = [40 50 60]

Example:

Condition can be passed as array as well. Consider the following example.

import numpy as np

x = np.asarray([[10, 20], [30, 40]])
y = np.asarray([[15, 15], [25, 25]])
cond = np.asarray([[True, True], [False, False]])

#applying where condition
z = np.where(cond, x, y)

#displaying the content of x, y and z
print("x =")
print(x)
print("\ny =")
print(y)
print("\nz =")
print(z)

The output of the above code will be:

x =
[[10 20]
 [30 40]]

y =
[[15 15]
 [25 25]]

z =
[[10 20]
 [25 25]]

❮ NumPy - Functions