问题
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