最“numpythonic”的方式是使用broadcasting。这是计算距离矩阵的一种快速而简单的方法,然后您可以获取绝对值的argmin
。
形状的
array1 = np.random.rand(4004001)
array2 = np.random.rand(1000)
# Calculate distance matrix (on truncated array1 for memory reasons)
dmat = array1[:400400] - array2[:,None]
# Take the abs of the distance matrix and work out the argmin along the last axis
ix = np.abs(dmat).argmin(axis=1)
dmat
:
(1000, 400400)
的形状ix
和内容:
(1000,)
array([237473, 166831, 72369, 11663, 22998, 85179, 231702, 322752, ...])
然而,它的内存饿了,如果你在一个去做这个手术了,居然不在我的8GB机器上处理您指定的阵列大小,这就是为什么我减小了array1
的大小的原因。
要使其在内存限制内工作,只需将其中一个数组切片为块,然后依次(或平行)在每个块上应用广播。在这种情况下,我将array2
分为10个区块:
# Define number of chunks and calculate chunk size
n_chunks = 10
chunk_len = array2.size // n_chunks
# Preallocate output array
out = np.zeros(1000)
for i in range(n_chunks):
s = slice(i*chunk_len, (i+1)*chunk_len)
out[s] = np.abs(array1 - array2[s, None]).argmin(axis=1)
首先对两个数组进行排序。然后遍历大数组,保持小数组中当前最接近的元素的索引。根据需要增加索引。如果itertools中有些东西会加快速度,我不会感到惊讶。 –
[在numpy数组中找到最接近的值]的可能重复(http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array) –