Numpy where
#
We sometimes want to know where a value is in an array.
import numpy as np
By “where” we mean, the position of the element that contains a particular value.
Here is an array.
arr = np.array([2, 99, -1, 4, 99])
arr
array([ 2, 99, -1, 4, 99])
As you know, we can use indexing to get elements using their index (position) in the array. In Python, array indices start at zero.
Here’s the value at index (position) 0:
arr[0]
2
We might also be interested to find which positions hold particular values.
In our array above, by reading, and counting positions, we can see that the values of 99 are in positions 1 and 4. We can ask for these elements by passing a list or an array between the square brackets, to index the array:
positions_with_99 = np.array([1, 4])
arr[positions_with_99]
array([99, 99])
Of course, we are already used to finding and then selecting elements according to various conditions, using Boolean vectors.
Here we identify the elements that contain 99. There is a True
at the
position where the array contains 99, and False
otherwise.
contains_99 = arr == 99
contains_99
array([False, True, False, False, True])
We can then get the 99 values with:
arr[contains_99]
array([99, 99])
Enter “where”#
Sometimes we really do need to know the index of the values that meet a certain condition.
In that case, you can use the Numpy where
function.
where
finds the index positions of the True
values in Boolean vectors.
indices = np.where(arr == 99)
indices
(array([1, 4]),)
We can use the returned indices
to index into the array, using square
brackets.
arr[indices]
array([99, 99])
Where summary#
Numpy where
returns the indices of True
values in a Boolean array.
You can use these indices to index into an array, and get the matching elements.