我尝试使用两个单独的DataFrame查找最近的上一个日期。我实际上已经获得了代码,但它使用了for
循环,我宁愿不使用它,特别是因为我的实际DataFrames会比下面的代码段大得多:
date_x = pd.to_datetime(['1/15/2015','2/14/2015','3/16/2015','4/15/2015','5/15/2015','6/14/2015','7/14/2015'])
date_y = pd.to_datetime(['1/1/2015','3/1/2015','6/14/2015','8/1/2015'])
dfx = pd.DataFrame({'date_x':date_x})
dfy = pd.DataFrame({'date_y':date_y})
z_list = []
for x in range(dfx['date_x'].count()):
z_list.append(dfy['date_y'][dfy['date_y'] <= dfx['date_x'][x]].max())
dfx['date_z'] = z_list
...产量
date_x date_z
0 2015-01-15 2015-01-01
1 2015-02-14 2015-01-01
2 2015-03-16 2015-03-01
3 2015-04-15 2015-03-01
4 2015-05-15 2015-03-01
5 2015-06-14 2015-06-14
6 2015-07-14 2015-06-14
这正是我想要的,但同样,我认为有更多的pandonic方式。
答案 0 :(得分:4)
尝试使用merge_asof()方法:
注意:此方法已添加到Pandas v.0.19.0
中In [17]: pd.merge_asof(dfx, dfy, left_on='date_x', right_on='date_y')
Out[17]:
date_x date_y
0 2015-01-15 2015-01-01
1 2015-02-14 2015-01-01
2 2015-03-16 2015-03-01
3 2015-04-15 2015-03-01
4 2015-05-15 2015-03-01
5 2015-06-14 2015-06-14
6 2015-07-14 2015-06-14