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

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

    The numpy_indexed package (disclaimer, I am its author) contains a vectorized equivalent of list.index for numpy.ndarray; that is:

    sequence_of_arrays = [[0, 1], [1, 2], [-5, 0]]
    arrays_to_query = [[-5, 0], [1, 0]]
    
    import numpy_indexed as npi
    idx = npi.indices(sequence_of_arrays, arrays_to_query, missing=-1)
    print(idx)   # [2, -1]
    

    This solution has vectorized performance, generalizes to ndarrays, and has various ways of dealing with missing values.

提交回复
热议问题