熊猫,根据最近的日期进行选择性加入

时间:2020-09-09 18:23:14

标签: python pandas

我有一个数据框X,其中包含以下内容

Index       A         B
2020-09-08  0.252167  0.263719  
2020-09-05  0.266898  0.270347
2019-09-04  0.254873  0.273878  

我还有另一个数据框Y,其中包含以下内容

Index       C
2021-09-08  0.252167   
2015-09-05  0.266898  

对于Y中的每一行,我想有效地选择X中最接近的行并将它们连接在一起。这里``最近''是索引的函数,即: 哪个日期更近。

在这种情况下,它应该返回。

Index       Index2     C          A         B
2021-09-08  2020-09-08 0.252167   0.252167  0.263719  
2015-09-05  2019-09-04 0.266898   0.254873  0.273878 

(注意:两个索引都是日期时间对象)

因为2020-09-08最接近2021-09-08,而2019-09-04最接近2015-09-05。

我可以通过遍历Y的每个索引并调用

来做到这一点

X.index.get_loc(currentYIndex,“最近”)

是否有更有效的方法?

1 个答案:

答案 0 :(得分:0)

这就像Quang的评论,但需要更多细节

df1['Index2']=df1['Index']
Out = pd.merge_asof(df2.sort_values('Index'), 
                    df1.sort_values('Index'), 
                    on = 'Index', 
                    direction = 'nearest', 
                    allow_exact_matches = False)
Out[33]: 
       Index         C         A         B     Index2
0 2015-09-05  0.266898  0.254873  0.273878 2019-09-04
1 2021-09-08  0.252167  0.252167  0.263719 2020-09-08
相关问题