Jack
Jack

Reputation: 1754

How to merge two dataframe base on dates which the datediff is one day?

Input

df1
 
id            A 
2020-01-01    10
2020-02-07    20
2020-04-09    30

df2
id           B
2019-12-31   50
2020-02-06   20
2020-02-07   70
2020-04-08   34
2020-04-09   44

Goal

df
id            A     B
2020-01-01    10   50
2020-02-07    20   20
2020-04-09    30   34

The detail as follows:

Upvotes: 2

Views: 199

Answers (2)

BENY
BENY

Reputation: 323226

Try pd.merge_asof

df = pd.merge_asof(df1,df2,on='id',tolerance=pd.Timedelta('1 day'),allow_exact_matches=False)
          id   A   B
0 2020-01-01  10  50
1 2020-02-07  20  20
2 2020-04-09  30  34

Upvotes: 1

cs95
cs95

Reputation: 402263

Could you simply add 1 day to df2's ID column before merging?

df1.merge(df2.assign(id=df2['id'] + pd.Timedelta(days=1)), on='id')

          id   A   B
0 2020-01-01  10  50
1 2020-02-07  20  20
2 2020-04-09  30  34

Upvotes: 1

Related Questions