Numpy 获取排序数组中的插入索引

Numpy get index of insertion in a sorted array

我正在尝试找到一种方法来创建一个传递两个数组的函数,其结果是一个索引数组,其中第一个数组的值将位于第二个数组中。下面的代码给出了我想要的结果,但我试图摆脱 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

您正在寻找np.searchsorted

indices = np.searchsorted(y_array, x_array)

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

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