Open In App

How to find the Index of value in Numpy Array ?

Last Updated : 13 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Using where() Method

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

Get the index of elements in the Python loop

Create a NumPy array and iterate over the array to compare the element in the array with the given array. If the element matches print the index.

Python3




import numpy as np
 
# create numpy array elements
a = np.array([2, 3, 4, 5, 6, 45, 67, 34])
 
# display element index where value = 45
 
index_of_element = -1
for i in range(a.size):
    if a[i] == 45:
        index_of_element = i
        break
 
if index_of_element != -1:
    print("element index  : ", index_of_element)
else:
    print("The element not present")


Output:

element index  : 5

Using ndenumerate() function to find the Index of value

It is usually used to find the first occurrence of the element in the given numpy array.

Python3




import numpy as np
def ind(array, item):
    for idx, val in np.ndenumerate(array):
        if val == item:
            return idx
    # If no item was found return None, other return types might be a problem due to
    # numbas type inference.
 
a = np.array([11, 12, 13, 14, 15, 16, 17, 15,
                11, 12, 14, 15, 16, 17, 18, 19, 20])
print(ind(a,11))


Output:

(6,)

Using enumerate() function to find the Index of value

Here we are using the enumerate function and then checking the value with the target value.

Python3




import numpy as np
a = np.array([11, 12, 13, 14, 15, 16, 17, 15,
              11, 12, 14, 15, 16, 17, 18, 19, 20])
print(next(i for i, x in
           enumerate(a) if x == 17))


Output:

6


Similar Reads

NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
Find the nearest value and the index of NumPy Array
In this article, let's discuss finding the nearest value and the index in an array with Numpy. We will make use of two of the functions provided by the NumPy library to calculate the nearest value and the index in the array. Those two functions are numpy.abs() and numpy.argmin(). Example Input Array: [12 40 65 78 10 99 30] Nearest value is to be fo
3 min read
NumPy ndarray.transpose() Method | Find Transpose of the NumPy Array
The ndarray.transpose() function returns a view of the array with axes transposed. For a 1-D array, this has no effect, as a transposed vector is simply the same vector.For a 2-D array, this is a standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted. If axes are not provided and arr.shape = (
2 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Select an element or sub array by index from a Numpy Array
The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements. Selecting a single element from a NumPy array Each element of these ndarrays can be accessed using its index number. Example: The following code shows how to a
2 min read
Difference between Numpy array and Numpy matrix
While working with Python many times we come across the question that what exactly is the difference between a numpy array and numpy matrix, in this article we are going to read about the same. What is np.array() in PythonThe Numpy array object in Numpy is called ndarray. We can create ndarray using numpy.array() function. It is used to convert a l
3 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Syntax: numpy.ndarray.size(arr) Parameters arr : [ar
1 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
Practice Tags :