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


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

The following code shows how to find the first index position of several values in a NumPy array:

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.

Additional Resources

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

How to Map a Function Over a NumPy Array
How to Convert NumPy Array to List in Python
How to Calculate the Magnitude of a Vector Using NumPy

Leave a Reply

Your email address will not be published. Required fields are marked *