【发布时间】:2019-08-07 00:59:14
【问题描述】:
我有 2 个不同长度的独立熊猫系列。
第一个和较短的有一组元素(浮点数)。对于每个元素,我希望找到与第二个和更大系列中的元素最接近的匹配(最小绝对差异)。
我也想知道第二个系列中最接近匹配元素的索引。
我尝试使用 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
【问题讨论】: