How to Find Index of Value in NumPy Array (With Examples)

In NumPy, you can use the numpy.where() method to find the index of a value in an array. This method takes an array and a value as arguments and returns the indices of the array where the given value is found. You can also use the numpy.argwhere() method to get the indices of all the elements with a given value. Examples of using both methods are provided to illustrate how to find the index of a value in a NumPy array.


You can use the following methods to find the index position of specific values in a NumPy array:

Method 1: Find All Index Positions of Value

np.where(x==value)

Method 2: Find First Index Position of Value

np.where(x==value)[0][0]

Method 3: Find First Index Position of Several Values

#define values of interest
vals = np.array([value1, value2, value3])

#find index location of first occurrence of each value of interest
sorter = np.argsort(x)
sorter[np.searchsorted(x, vals, sorter=sorter)]

The following examples show how to use each method in practice.

Method 1: Find All Index Positions of Value

The following code shows how to find every index position that is equal to a certain value in a NumPy array:

import numpy as np

#define array of values
x = np.array([4, 7, 7, 7, 8, 8, 8])

#find all index positions where x is equal to 8
np.where(x==8)

(array([4, 5, 6]),)

From the output we can see that index positions 4, 5, and 6 are all equal to the value 8.

Method 2: Find First Index Position of Value

The following code shows how to find the first index position that is equal to a certain value in a NumPy array:

import numpy as np

#define array of values
x = np.array([4, 7, 7, 7, 8, 8, 8])

#find first index position where x is equal to 8
np.where(x==8)[0][0]

4

From the output we can see that the value 8 first occurs in index position 4.

Method 3: Find First Index Position of Several Values

import numpy as np

#define array of values
x = np.array([4, 7, 7, 7, 8, 8, 8])

#define values of interest
vals = np.array([4, 7, 8])

#find index location of first occurrence of each value of interest
sorter = np.argsort(x)
sorter[np.searchsorted(x, vals, sorter=sorter)]

array([0, 1, 4])

From the output we can see:

  • The value 4 first occurs in index position 0.
  • The value 7 first occurs in index position 1.
  • The value 8 first occurs in index position 4.

The following tutorials explain how to perform other common operations in NumPy:

x