【问题标题】:Find multiple values within a Numpy array在 Numpy 数组中查找多个值
【发布时间】:2012-03-05 12:24:28
【问题描述】:

我正在寻找一个 numpy 函数来查找在向量 (xs) 中找到某些值的索引。这些值在另一个数组 (ys) 中给出。返回的索引必须遵循 ys 的顺序。

在代码中,我想用一个 numpy 函数替换下面的列表理解。

>> import numpy as np
>> xs = np.asarray([45, 67, 32, 52, 94, 64, 21])
>> ys = np.asarray([67, 94])
>> ndx = np.asarray([np.nonzero(xs == y)[0][0] for y in ys]) # <---- This line
>> print(ndx)
[1 4]

有没有快速的方法?

谢谢

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    对于大数组xsys,您需要更改基本方法以使其变得更快。如果您对xs 排序没问题,那么一个简单的选择是使用numpy.searchsorted()

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

    如果保持xs的原始顺序很重要,您也可以使用这种方法,但您需要记住原始索引:

    orig_indices = xs.argsort()
    ndx = orig_indices[numpy.searchsorted(xs[orig_indices], ys)]
    

    【讨论】:

    • 如果您不需要跟踪找到了哪些元素以及没有找到哪些元素,您可以过滤输出以摆脱超出限制的所有索引:ndx = [ e for e in np .searchsorted(xs,ys) if e
    【解决方案2】:

    在这种情况下,只需轻松使用np.isin() 函数来屏蔽那些符合您条件的元素,如下所示:

    xs = np.asarray([45, 67, 32, 52, 94, 64, 21])
    ys = np.asarray([67, 94])
    
    mask=xs[np.isin(xs,xy)]
    print(xs[mask])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 2016-12-05
      • 1970-01-01
      • 2021-03-05
      相关资源
      最近更新 更多