Is there a NumPy function to return the first index of something in an array?

前端 未结 13 1627
萌比男神i
萌比男神i 2020-11-22 05:55

I know there is a method for a Python list to return the first index of something:

>>> l = [1, 2, 3]
>>> l.index(2)
1

Is

13条回答
  •  旧巷少年郎
    2020-11-22 06:11

    Yes, given an array, array, and a value, item to search for, you can use np.where as:

    itemindex = numpy.where(array==item)
    

    The result is a tuple with first all the row indices, then all the column indices.

    For example, if an array is two dimensions and it contained your item at two locations then

    array[itemindex[0][0]][itemindex[1][0]]
    

    would be equal to your item and so would be:

    array[itemindex[0][1]][itemindex[1][1]]
    

提交回复
热议问题