Tobitor
Tobitor

Reputation: 1508

How to merge pandas dataframes on datetime index and two columns

I have two dataframes which look like this:

df1
index A B
01-01-2021 1 2
01-02-2021 2 3
01-03-2021 5 5
01-04-2021 8 7

df2
index B A
01-03-2021 5 5
01-04-2021 7 8
01-05-2021 11 0
01-06-2021 2 9

I would like to merge them by datetime index and the columns A and B. The merged dataframe df should look like this:

df

index A B
01-01-2021 1 2
01-02-2021 2 3
01-03-2021 5 5
01-04-2021 8 7
01-05-2021 0 11
01-06-2021 9 2

How can I do this?

Upvotes: 2

Views: 114

Answers (1)

jezrael
jezrael

Reputation: 862431

Use concat and then remove duplicated rows by duplicated index:

df = pd.concat([df1, df2])
df = df[~df.index.duplicated()]
print (df)
            A   B
index            
2021-01-01  1   2
2021-01-02  2   3
2021-01-03  5   5
2021-01-04  8   7
2021-01-05  0  11
2021-01-06  9   2

Upvotes: 3

Related Questions