﻿ 查找一个数组的最近索引与另一个数组中的所有值 – Python/NumPy - 代码日志

#### 查找一个数组的最近索引与另一个数组中的所有值 – Python/NumPy

``````import numpy as np

refArray = np.random.random(16);
myArray = np.random.random(1000);

def find_nearest(array, value):
idx = (np.abs(array-value)).argmin()
return idx;

for value in np.nditer(myArray):
index = find_nearest(refArray, value);
print(index);
``````

``````def closest_argmin(A, B):
L = B.size
sidx_B = B.argsort()
sorted_B = B[sidx_B]
sorted_idx = np.searchsorted(sorted_B, A)
sorted_idx[sorted_idx==L] = L-1
mask = (sorted_idx > 0) & \
((np.abs(A - sorted_B[sorted_idx-1]) < np.abs(A - sorted_B[sorted_idx])) )
``````

>获取左侧位置的排序索引.我们这样做 – np.searchsorted(arr1,arr2,side =’left’)或者只是np.searchsorted(arr1,arr2).现在,searchsorted期望排序数组作为第一个输入,所以我们需要一些准备工作.
>将这些左侧位置的值与其右侧位置(左侧1)的值进行比较,并查看哪一个最接近.我们在计算掩码的步骤中执行此操作.
>根据左边的或右边的最近的,选择相应的.这是通过减去索引来完成的,掩码值作为偏移量被转换为整数.

``````def org_app(myArray, refArray):
out1 = np.empty(myArray.size, dtype=int)
for i, value in enumerate(myArray):
# find_nearest from posted question
index = find_nearest(refArray, value)
out1[i] = index
return out1
``````

``````In [188]: refArray = np.random.random(16)
...: myArray = np.random.random(1000)
...:

In [189]: %timeit org_app(myArray, refArray)
100 loops, best of 3: 1.95 ms per loop

In [190]: %timeit closest_argmin(myArray, refArray)
10000 loops, best of 3: 36.6 µs per loop

In [191]: np.allclose(closest_argmin(myArray, refArray), org_app(myArray, refArray))
Out[191]: True
``````