In NumPy, you can find the index of a specific value in an array using the numpy.where()
function or by using boolean indexing.
Python finds the index of the value in a numpy array example
Here’s a more detailed example of finding the index of a value in a NumPy array using both the numpy.where()
function and boolean indexing:
Using numpy.where()
:
import numpy as np
# Create a NumPy array
arr = np.array([10, 20, 30, 40, 50])
# Find the index of a specific value, e.g., 30
value_to_find = 30
indices = np.where(arr == value_to_find)[0]
if indices.size > 0:
print("Value found at index:", indices[0])
else:
print("Value not found in the array.")
Using boolean indexing:
import numpy as np
# Create a NumPy array
arr = np.array([10, 20, 30, 40, 50])
# Find the index of a specific value, e.g., 30
value_to_find = 30
indices = np.where(arr == value_to_find)[0]
if indices.size > 0:
print("Value found at index:", indices[0])
else:
print("Value not found in the array.")
Output:
Both of these methods will return the index (or indices) where the specified value is found in the array. Note that if the value appears multiple times in the array, both methods will return all the indices where the value is found. In the example above, if you have arr = np.array([10, 30, 30, 40, 50])
, both methods would return indices 1
and 2
for the value 30
.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.