The Numpy module provides a function to select elements based on conditions. To work with an array in Python, use the Numpy library.
Unfortunately, it does not come with Python by default, and you need to install it first and then import it at the head of the Python file to use its methods.
np.where
The np.where() is a numpy library method that returns the indices of elements in an input array where the given condition is satisfied. The numpy.where() function iterates over a bool array, and for every True, it yields the element array x. For every False, it yields the corresponding item from array y.
The np.where() function returns an array of elements from x where the condition is True and elements from y elsewhere. To find an index in the Numpy array, use the np.where() function.
Syntax
numpy.where(condition[, x, y])
Parameters
condition: A conditional expression that returns the Numpy array of bool
x, y: Arrays (Optional, i.e., either both are passed or not passed)
- If all arguments –> condition, x & y are given in numpy.where() it will return items selected from x & y depending on values in the bool array yielded by the condition. All 3 arrays must be of the same size.
- If x and y arguments are not passed, and only the condition argument is passed, then it returns the tuple of arrays (one for each axis) containing the indices of the True items in the bool numpy array returned by the condition.
Example
See the following code.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]) result = np.where(arr == 19) print('Tuple of arrays returned : ', result) print("Elements with value 19 exists at following indices", result[0], sep='\n')
Output
python3 app.py Tuple of arrays returned : (array([8]),) Elements with value 19 exists at following indices [8]
Find the index of a value in a 1D Numpy array.
The numpy array element with value 19 occurs at different places. But first, let’s see all its indices.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 19, 13, 14, 15, 11, 19, 21, 19, 20, 21]) result = np.where(arr == 19) print('Tuple of arrays returned : ', result) print("Elements with value 19 exists at following indices", result[0], sep='\n')
Output
python3 app.py Tuple of arrays returned : (array([1, 6, 8]),) Elements with value 19 exists at following indices [1 6 8]
The result is a tuple of arrays (one for each axis) containing the indices where value 19 exists in the array.
Get the first index of the element with the value 19.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 19, 13, 14, 15, 11, 19, 21, 19, 20, 21]) result = np.where(arr == 19) print('Tuple of arrays returned: ', result) print("Elements with value 19 first exists at index:", result[0][0])
Output
python3 app.py Tuple of arrays returned: (array([1, 6, 8]),) Elements with value 19 first exists at index: 1
Python numpy.where(), elements of the NumPy array ndarray that satisfy the conditions can be replaced or performed specified processing.
What If the element is not found in the numpy array
If the given item doesn’t exist in a numpy array, then the returned array of indices will be empty.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 19, 13, 14, 15, 11, 19, 21, 19, 20, 21]) result = np.where(arr == 46) print('Tuple of arrays returned: ', result) print("Elements with value 19 first exists at index:", result[0][0])
Output
python3 app.py Tuple of arrays returned: (array([], dtype=int64),) Traceback (most recent call last): File "app.py", line 9, in <module> print("Elements with value 19 first exists at index:", result[0][0]) IndexError: index 0 is out of bounds for axis 0 with size 0
Find an index of a value in a 2D Numpy array in Python
Let’s create a 2D numpy array. See the following code example.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([[11, 19, 18], [14, 15, 11], [19, 21, 46], [29, 21, 19]]) result = np.where(arr == 19) print('Tuple of arrays returned: ', result) print("Elements with value 19 first exists at index:", result[0][0])
Output
python3 app.py Tuple of arrays returned: (array([0, 2, 3]), array([1, 0, 2])) Elements with value 19 first exists at index: 0
It returns the tuple of arrays, one for each dimension. Like in our case, it’s a two-dimension array, so numpy.where() will return the tuple of two arrays.
The length of both arrays will be the same. So to get a list of exact indices, we can zip these arrays.
See the following code.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([[11, 19, 18], [14, 15, 11], [19, 21, 46], [29, 21, 19]]) result = np.where(arr == 19) listOfIndices= list(zip(result[0], result[1])) for indice in listOfIndices: print(indice)
Output
python3 app.py (0, 1) (2, 0) (3, 2)
How to get indices of elements based on multiple conditions in Numpy
When can also pass multiple conditions to numpy.where() function. For example, get the indices of elements with a value of less than 21 and greater than 15.
# app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 19, 18, 14, 15, 11, 19, 21, 46, 29, 21, 19]) result = np.where((arr > 15) & (arr < 21)) print(result)
Output
python3 app.py (array([ 1, 2, 6, 11]),)
The above example will return the element values less than 21 and more than 14.
I have the following but is not working.
>>>INPUT
def search(c):
pos = np.where(elem == c)
print(pos)
elem = np.array([[‘one’, ‘two’, ‘three’]])
t=’one’
search(t)
>>>>OUTPUT
pos (array([], dtype=int64),)