2

I'm trying to find the nearest previous date using two separate DataFrames. I've actually got the code to do it, but it uses a for loop, which I would rather not use, especially as my actual DataFrames will be considerably larger than the following snippet:

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

yields...

      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

which is exactly what I want, but again, I think there is a more pandonic way.

elPastor
  • 8,435
  • 11
  • 53
  • 81

1 Answers1

5

Try to use merge_asof() method:

NOTE: this method has been added in 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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419