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

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

    Just to add a very performant and handy numba alternative based on np.ndenumerate to find the first index:

    from numba import njit
    import numpy as np
    
    @njit
    def index(array, item):
        for idx, val in np.ndenumerate(array):
            if val == item:
                return idx
        # If no item was found return None, other return types might be a problem due to
        # numbas type inference.
    

    This is pretty fast and deals naturally with multidimensional arrays:

    >>> arr1 = np.ones((100, 100, 100))
    >>> arr1[2, 2, 2] = 2
    
    >>> index(arr1, 2)
    (2, 2, 2)
    
    >>> arr2 = np.ones(20)
    >>> arr2[5] = 2
    
    >>> index(arr2, 2)
    (5,)
    

    This can be much faster (because it's short-circuiting the operation) than any approach using np.where or np.nonzero.


    However np.argwhere could also deal gracefully with multidimensional arrays (you would need to manually cast it to a tuple and it's not short-circuited) but it would fail if no match is found:

    >>> tuple(np.argwhere(arr1 == 2)[0])
    (2, 2, 2)
    >>> tuple(np.argwhere(arr2 == 2)[0])
    (5,)
    

提交回复
热议问题