根据第二个系列的值和这些最接近匹配的位置(索引)查找系列的元素方面最接近的匹配

Finding element-wise closest match of a series with respect to values of a second series and the locations (index) of these closest matches

我有 2 个不同的 pandas 系列,长度不同。

第一个和较短的一个有一组元素(浮点数)。对于每个元素,我希望找到与第二个和更大系列中的元素最接近的匹配(最小绝对差)。

我也想知道第二个系列中最接近的匹配元素的索引。

我尝试使用 reindex 方法,但它抛出了一个错误 'ValueError: cannot reindex a non-unique index with a method or limit' 因为第二个系列具有非唯一值,这些值被设置为索引。

这是我用来尝试找到 B 系列元素与 A 系列元素最接近匹配的代码。

A = pd.Series([1.0, 4.0, 10.0, 4.0, 5.0, 19.0, 20.0])
B = pd.Series([0.8, 5.1, 10.1, 0.3, 5.5])
pd.Series(A.values, A.values).reindex(B.values, method='nearest')

ValueError: cannot reindex a non-unique index with a method or limit

最后,我希望有一个像下面这样的数据框。

B    Closest_match_in_Series_A  Index_of_closest_match_in Series_A
0.8  1.0                        0
5.1  5.0                        4
10.1 10.0                       2
0.3  1.0                        0
5.5  5.0                        4

所以这是使用 numpy 广播

的一种方法
A.iloc[np.abs(B.values-A.values[:,None]).argmin(axis=0)]

0     1.0
4     5.0
2    10.0
0     1.0
4     5.0
dtype: float64

这里是添加 drop_duplicates

的修复
pd.Series(A.values, A.values).sort_index().drop_duplicates().reindex(B.values, method='nearest')
0.8      1.0
5.1      5.0
10.1    10.0
0.3      1.0
5.5      5.0
dtype: float64