Retrieve indexes of multiple values with Numpy in a vectorization way

喜欢而已 提交于 2020-01-16 15:47:47

问题


In order to get the index corresponding to the "99" value in a numpy array, we do :

mynumpy=([5,6,9,2,99,3,88,4,7))
np.where(my_numpy==99)

What if, I want to get the index corresponding to the following values 99,55,6,3,7? Obviously, it's possible to do it with a simple loop but I'm looking for a more vectorization solution. I know Numpy is very powerful so I think it might exist something like that.

desired output :

searched_values=np.array([99,55,6,3,7])
np.where(searched_values in mynumpy)
[(4),(),(1),(5),(8)]

回答1:


Here's one approach with np.searchsorted -

def find_indexes(ar, searched_values, invalid_val=-1):
    sidx = ar.argsort()
    pidx = np.searchsorted(ar, searched_values, sorter=sidx)
    pidx[pidx==len(ar)] = 0
    idx = sidx[pidx]
    idx[ar[idx] != searched_values] = invalid_val
    return idx

Sample run -

In [29]: find_indexes(mynumpy, searched_values, invalid_val=-1)
Out[29]: array([ 4, -1,  1,  5,  8])

For a generic invalid value specifier, we could use np.where -

def find_indexes_v2(ar, searched_values, invalid_val=-1):
    sidx = ar.argsort()
    pidx = np.searchsorted(ar, searched_values, sorter=sidx)
    pidx[pidx==len(ar)] = 0
    idx = sidx[pidx]
    return np.where(ar[idx] == searched_values, idx, invalid_val)

Sample run -

In [35]: find_indexes_v2(mynumpy, searched_values, invalid_val=None)
Out[35]: array([4, None, 1, 5, 8], dtype=object)

# For list output
In [36]: find_indexes_v2(mynumpy, searched_values, invalid_val=None).tolist()
Out[36]: [4, None, 1, 5, 8]


来源:https://stackoverflow.com/questions/49067127/retrieve-indexes-of-multiple-values-with-numpy-in-a-vectorization-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!