import numpy as np

Searching NumPy Arrays with np.where()ΒΆ

np.where(condition) returns the indices of elements that satisfy a given condition. For example, np.where(arr == 3) returns a tuple of arrays containing the positions where the value 3 appears. This is different from boolean indexing which returns the values themselves – np.where() gives you the locations. Knowing indices is valuable when you need to cross-reference positions across multiple arrays, locate specific data points for inspection, or implement conditional logic based on position rather than value.

# Search
np1 = np.array([1,2,3,4,5,6,7,8,9,10, 3])
x = np.where(np1 == 3)

Retrieving Search ResultsΒΆ

np.where() returns a tuple of index arrays. Access the first element x[0] to get the actual index positions. You can then use these indices to retrieve the matching values from the original array with np1[x[0]].

Finding Even and Odd NumbersΒΆ

Combining np.where() with the modulus operator % is a practical pattern for partitioning data by a condition. np.where(np1 % 2 == 0) finds indices of all even numbers, while np.where(np1 % 2 == 1) finds odd numbers. This technique generalizes to any condition – finding multiples, values in a range, or elements matching a pattern.

# return all the odd numbers
z = np.where(np1 % 2 == 1)
print(np1)
print(z[0])