我有 2 个不同长度的独立 pandas 系列。
第一个和较短的一个有一组元素( float )。对于每个元素,我希望找到与第二个和更大系列中的元素最接近的匹配(最小绝对差异)。
我还想知道第二个系列中最接近的匹配元素的索引。
我尝试使用重新索引方法,但它会抛出错误“ValueError:无法使用方法或限制重新索引非唯一索引”,因为第二个系列具有设置为索引的非唯一值。
这是我用来尝试找到 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
关于python - 根据第二个系列的值和这些最接近匹配的位置(索引)查找系列的元素方面最接近的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385687/