asimo
asimo

Reputation: 2500

Populating values from another dataframe whilst comparing datetimes

I have two dataframes of the below nature:

df1
Index    Date          NextEntry_Date
0        2018-01-25
1        2018-02-25
2        2018-03-25
3        2018-04-25
4        2018-05-25
5        2018-06-25
6        2018-07-25
7        2018-08-25
8        2018-09-25
9        2018-10-25


df2
Index    Date 
2000    2018-07-20
2500    2019-07-20
2800    2020-07-20

I want to populate the NextEntry_Date column such that the df1 looks like below

     df1
Index    Date          NextEntry_Date
0        2018-01-25    2018-07-20
1        2018-02-25    2018-07-20
2        2018-03-25    2018-07-20
3        2018-04-25    2018-07-20
4        2018-05-25    2018-07-20
5        2018-06-25    2018-07-20
6        2018-07-25    **2019-07-20**
7        2018-08-25    2019-07-20
8        2018-09-25    2019-07-20
9        2018-10-25    2019-07-20

Can you please advise... Is there a way other than writing loops ?

Upvotes: 2

Views: 28

Answers (1)

jpp
jpp

Reputation: 164693

This is one way using pandas.cut:

# convert columns to datetime, if not already done
df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])

# get bins as list, adding one to the top for the earlier dates
bins = [pd.to_datetime('07-20-2017')] + df2['Date'].tolist()

# use pandas.cut to map bins with labels
df1['NextEntry_Date'] = pd.cut(df1['Date'], bins, labels=df2['Date'])

print(df1)

   Index       Date NextEntry_Date
0      0 2018-01-25     2018-07-20
1      1 2018-02-25     2018-07-20
2      2 2018-03-25     2018-07-20
3      3 2018-04-25     2018-07-20
4      4 2018-05-25     2018-07-20
5      5 2018-06-25     2018-07-20
6      6 2018-07-25     2019-07-20
7      7 2018-08-25     2019-07-20
8      8 2018-09-25     2019-07-20
9      9 2018-10-25     2019-07-20

Upvotes: 1

Related Questions