Find multiple values within a Numpy array

后端 未结 2 1493
梦如初夏
梦如初夏 2021-01-04 03:53

I am looking for a numpy function to find the indices at which certain values are found within a vector (xs). The values are given in another array (ys). The returned indice

相关标签:
2条回答
  • 2021-01-04 04:11

    In this kind of cases, just easily use np.isin() function to mask those elements conform your conditions, like this:

    xs = np.asarray([45, 67, 32, 52, 94, 64, 21])
    ys = np.asarray([67, 94])
    
    mask=xs[np.isin(xs,xy)]
    print(xs[mask])
    
    0 讨论(0)
  • 2021-01-04 04:13

    For big arrays xs and ys, you would need to change the basic approach for this to become fast. If you are fine with sorting xs, then an easy option is to use numpy.searchsorted():

    xs.sort()
    ndx = numpy.searchsorted(xs, ys)
    

    If it is important to keep the original order of xs, you can use this approach, too, but you need to remember the original indices:

    orig_indices = xs.argsort()
    ndx = orig_indices[numpy.searchsorted(xs[orig_indices], ys)]
    
    0 讨论(0)
提交回复
热议问题