np.where: How to Find an Index of Value in Numpy Array

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)

  1. 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.
  2. 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.

1 thought on “np.where: How to Find an Index of Value in Numpy Array”

  1. 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),)

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.