How to Querying Numpy Arrays Using the Where() Method in Python

Published on Aug. 22, 2023, 12:16 p.m.

To query NumPy arrays using the where() method in Python, you can use the following syntax:

import numpy as np

# create a sample NumPy array
arr = np.array([1, 2, 3, 4, 5])

# use the where() method to query the array
indices = np.where(arr > 3)

# view the indices where the condition is true
print(indices)

In this example, we first created a sample NumPy array, and then used the where() method to query the array for elements greater than 3. The where() method returns a tuple of arrays, with each array containing the indices where the condition is true along a particular axis. In this case, since we are using a 1D array, the tuple contains only one array with the indices where the condition is true. We then printed out these indices using the print() statement.

The where() method can be used to query multidimensional arrays as well, with the ability to specify the axis along which to search for the condition. Overall, the where() method is a useful tool for querying NumPy arrays in Python.

Tags: