且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NumPy的:矢量找到最接近的值在数组中的另一个阵列中的每个元素

更新时间:2021-11-27 23:30:15

例如,你可以在计算上的所有分歧去:

For example, you can compute all the differences in on go with:

differences = (test_array.reshape(1,-1) - known_array.reshape(-1,1))

和使用 argmin 并随着 np.diagonal 花哨的索引,以获得所需的指标和不同之处:

And use argmin and fancy indexing along with np.diagonal to get desired indices and differences:

indices = np.abs(differences).argmin(axis=0)
residual = np.diagonal(differences[indices,])

因此​​,对于

So for

>>> known_array = np.array([-24, -18, -13, -30,  29])
>>> test_array = np.array([-6,  4, -6,  4,  8, -4,  8, -6,  2,  8])

一赠

>>> indices
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
>>> residual
array([ 7, 17,  7, 17, 21,  9, 21,  7, 15, 21])