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

前端 未结 13 1903
萌比男神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:23

    If you're going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don't need explicit indices. The absolute simplest way to do this is to simply index based on a truth value.

    other_array[first_array == item]
    

    Any boolean operation works:

    a = numpy.arange(100)
    other_array[first_array > 50]
    

    The nonzero method takes booleans, too:

    index = numpy.nonzero(first_array == item)[0][0]
    

    The two zeros are for the tuple of indices (assuming first_array is 1D) and then the first item in the array of indices.

提交回复
热议问题