Home >Backend Development >Python Tutorial >How to Find the Index of the First Occurrence of an Element in a NumPy Array?
Finding the First Occurrence of an Element in a NumPy Array
Similar to Python lists, NumPy arrays provide a convenient method to locate the first occurrence of a specified value or item. However, unlike Python lists, the syntax for determining the index of an element in an array slightly differs.
To retrieve the index of the first instance of an element within a NumPy array, you can employ the np.where function. np.where takes two arguments: the array itself and the value you wish to locate.
itemindex = numpy.where(array == item)
The returned result is a tuple containing two arrays: one comprising row indices, and the other comprising column indices. To access the actual index of the first occurrence of your item, you can utilize the subscripting operator, using the first element of each array in the tuple.
For instance, in a two-dimensional array, where your item appears twice, you can access these occurrences as follows:
array[itemindex[0][0]][itemindex[1][0]]
and
array[itemindex[0][1]][itemindex[1][1]]
Both expressions will return the value of your item.
The above is the detailed content of How to Find the Index of the First Occurrence of an Element in a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!