Finding the First Index of an Array Element
Similar to Python lists, NumPy arrays offer a method for locating the first occurrence of a specific value. This question delves into the NumPy equivalent of the list.index() method.
NumPy's Index Retrieval Method
To retrieve the index of the first element in a NumPy array that matches a given value, utilize the np.where function:
itemindex = np.where(array == item)
This function returns a tuple containing two arrays:
This tuple provides the necessary coordinates to access the matching element within the array.
Example Usage
Consider a two-dimensional array:
array = np.array([[1, 2, 3], [4, 5, 6]])
If we want to find the first occurrence of the value 5, we can use:
itemindex = np.where(array == 5) print(itemindex[0][0], itemindex[1][0]) # Output: 1 1
This indicates that the value 5 is located at row index 1 and column index 1 within the array, which can be confirmed by:
print(array[itemindex[0][0]][itemindex[1][0]]) # Output: 5
The above is the detailed content of How to Find the First Index of an Element in a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!