【问题标题】:Finding element-wise closest match of a series with respect to values of a second series and the locations (index) of these closest matches根据第二个系列的值和这些最接近匹配的位置(索引)查找系列的元素最接近匹配
【发布时间】: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

【问题讨论】:

    标签: python pandas series


    【解决方案1】:

    所以这是使用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
    

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2011-03-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多