Numpy equivalent of list.index

前端 未结 6 2257
粉色の甜心
粉色の甜心 2021-02-12 11:48

In a low-level function that is called many times, I need to do the equivalent of python\'s list.index, but with a numpy array. The function needs to return when it finds the f

6条回答
  •  悲哀的现实
    2021-02-12 12:10

    See my comment on the OP's question for caveats, but in general, I would do the following:

    import numpy as np
    a = np.array([1, 2, 3])
    np.min(np.nonzero(a == 2)[0])
    

    if the value you are looking for is not in the array, you'll get a ValueError due to:

    ValueError: zero-size array to ufunc.reduce without identity
    

    because you are trying to take the min value of an empty array.

    I would profile this code and see if it is an actual bottleneck, because in general when numpy searches through an entire array using a built-in function rather than an explicit python loop, it is relatively fast. An insistence on halting the search when it finds the first value may be functionally irrelevant.

提交回复
热议问题