Skip to main content
numpy.where() in Python

numpy.where() in Python

The numpy module in Python has a function that allows you to select elements based on circumstances. This method helps the user in determining the location of the element in the array that has been entered that meets the stated conditions.

np.where with example

The numpy.where() function returns the indices of elements in an input array where the given condition is satisfied.

Syntax :

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

Parameters:

condition : When True, yield x, otherwise yield y.

Let’s go through some examples to demonstrate this in different scenarios.

numpy.where with 1D Arrays

Let’s create a simple 1-dimensional array. This array will be the square of sequential integers. I’ve squared the integers so that the values in the array do not correspond directly to the values of the array indices.

import numpy as np
a1 = np.arange(10)
print(a1)
fa = np.where(a1 > 3)
print(fa)

Output:

[0 1 2 3 4 5 6 7 8 9]
(array([4, 5, 6, 7, 8, 9]),)

The first step is to import Python’s numpy module.

define a single dimensional array from 1 to 10.

we can use np.where to identify the array indices where a1 is greater than 3. The result is a tuple with a single array that contains index values 2 and greater.

numpy.where with 2D Arrays

Let’s create a 2D array that is similar to the 1D array. The following code creates a numpy array with 4 rows and 3 columns.

import numpy as np
a2 = np.arange(12).reshape((4, 3))
print(a2)
fa = np.where(a2 > 7)
print(fa)

Output:

[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
(array([2, 3, 3, 3]), array([2, 0, 1, 2]))

** Process exited – Return Code: 0 **
Press Enter to exit terminal

Leave a Reply

Your email address will not be published. Required fields are marked *