MrC*_*ean 2 python numpy insertion
我试图找到一种方法来创建一个传递两个数组的函数,其中结果是一个索引数组,其中第一个数组中的值将位于第二个数组中。下面的代码给出了我想要的结果,但我试图摆脱循环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]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
您正在寻找np.searchsorted:
indices = np.searchsorted(y_array, x_array)
Run Code Online (Sandbox Code Playgroud)
唯一的区别是,如果超过最大元素,则返回数组的大小:
>>> indices
array([0, 1, 0, 3, 5], dtype=int64)
Run Code Online (Sandbox Code Playgroud)
如果需要取而代之-1,可以使用np.where或者直接屏蔽:
indices = np.where(indices < y_array.size, indices, -1)
Run Code Online (Sandbox Code Playgroud)
或者
indices[indices >= y_array.size] = -1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
679 次 |
| 最近记录: |