How to use where() Method In Python

where() method is used to specify the index of a particular element specified in the condition.

Syntax: numpy.where(condition[, x, y])

Example 1: Get index positions of a given value

Here, we find all the indexes of 3 and the index of the first occurrence of 3, we get an array as output and it shows all the indexes where 3 is present.

Python3




# import numpy package
import numpy as np
 
# create an numpy array
a = np.array([1, 2, 3, 4, 8, 6, 7, 3, 9, 10])
 
# display index value of 3
print("All index value of 3 is: ", np.where(a == 3)[0])
 
print("First index value of 3 is: ",np.where(a==3)[0][0])


Output:

All index value of 3 is:  [2 7]
First index value of 3 is:  2

Example 2: Print First Index Position of Several Values

Here, we are printing the index number of all values present in the values array.

Python3




# import numpy package
import numpy as np
 
# create an numpy array
a = np.array([1, 2, 3, 4, 8, 6, 2, 3, 9, 10])
 
values = np.array([2, 3, 10])
  
# index of first occurrence of each value
sorter = np.argsort(a)
 
print("index of first occurrence of each value: ",
      sorter[np.searchsorted(a, values, sorter=sorter)])


Output:

index of first occurrence of each value:  [1 2 9]

Example 3: Get the index of elements based on multiple conditions

Get the index of elements with a value less than 20 and greater than 12

Python3




# Create a numpy array
a = np.array([11, 12, 13, 14, 15, 16, 17, 15,
                11, 12, 14, 15, 16, 17, 18, 19, 20])
 
# Get the index of elements with value less
# than 20 and greater than 12
print("Index of elements with value less\
        than 20 and greater than 12 are: \n",
      np.where((a > 12) & (a < 20)))


Output:

Index of elements with value less than 20 and greater than 12 are: 
 (array([ 2,  3,  4,  5,  6,  7, 10, 11, 12, 13, 14, 15], dtype=int64),)

How to find the Index of value in Numpy Array ?

In this article, we are going to find the index of the elements present in a Numpy array.

Similar Reads

Using where() Method

where() method is used to specify the index of a particular element specified in the condition....

Get the index of elements in the Python loop

...

Using ndenumerate() function to find the Index of value

...

Using enumerate() function to find the Index of value

...

Contact Us