【问题标题】:Numpy get index of insertion in a sorted arrayNumpy获取排序数组中的插入索引
【发布时间】:2020-12-20 22:59:45
【问题描述】:

我试图找到一种方法来创建一个传递两个数组的函数,其中结果是一个索引数组,其中第一个数组的值将位于第二个数组中。下面的代码给出了我想要的结果,但我试图摆脱 for 循环并找到一种使用 numpy 函数对其进行矢量化的方法:

x_array = np.array([25, 32, 3, 99, 300])
y_array = np.array([30, 33, 56, 99, 250])

result = [0, 1, 0, 3, -1]
def get_index(x_array, y_array):
   result = []
   for x  in x_array:
       index = np.where(x <= y_array)[0]
       if index.size != 0:
           result.append(index.min())
       else:
           result.append(-1)
   return result

【问题讨论】:

  • 第二个数组是否始终排序,并且您正在寻找插入索引?

标签: python numpy insertion


【解决方案1】:

您正在寻找np.searchsorted:

indices = np.searchsorted(y_array, x_array)

唯一的区别是,如果超过最大元素,这将返回数组的大小:

>>> indices
array([0, 1, 0, 3, 5], dtype=int64)

如果需要获取-1,可以使用np.where或者直接屏蔽:

indices = np.where(indices < y_array.size, indices, -1)

indices[indices >= y_array.size] = -1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多