How to find index of element in NumPy array

You can find the index of an element in the NumPy array with the following code. I highly recommend you the “Python Crash Course Book” to learn Python. In this article, you’ll see the four examples with solutions. These examples are:

  • Find the index of an element in a 1D NumPy array
  • Index of the element in a 2D NumPy array
  • Index based on multiple conditions
  • The first index of an element in an array

Example 1: Index of an element in 1D Numpy array

# Import the NumPy library as np
import numpy as np

# Create a 1D NumPy array
a = np.array([5, 10, 15, 20, 5, 10])

# Index of a value
index = np.argwhere(a == 5)

# Display the output
print(index)

Output:

[[0]
 [4]]

Example 2: Index of an element in 2d array Python

# Import the NumPy library as np
import numpy as np

# Create a 2D NumPy array
a = np.array([[5, 10, 15, 20, 10],
              [10, 20, 30, 40, 5]])

# Index of a value
index = np.argwhere(a == 10)

# Display the output
print(index)

Output:

[[0 1]
 [0 4]
 [1 0]]

Example 3: Selection based on multiple conditions

# Import the NumPy library as np
import numpy as np

# Create a 1D NumPy array
a = np.array([5, 10, 15, 20, 10, 30])

# Index of a value
index = np.argwhere((a > 10) & (a < 20))

# Display the output
print(index)

Output:

[[2]]

Example 4: First index of an element in an array

# Import the NumPy library as np
import numpy as np

# Create a 1D NumPy array
a = np.array([5, 10, 15, 20, 10, 30])

# Index of a value
index = np.argwhere(a == 10)

if len(index) > 0:
    # Display the output
    print(index[0][0])

Output:

1

Leave a Comment

Your email address will not be published.