Home > Software engineering >  Concatenate two df with same kind of index
Concatenate two df with same kind of index

Time:03-11

I have two df.

df1:

         date   a
0   2021-12-15  0.16
1   2021-12-16  0.16
2   2021-12-17  0.16

df2:

         date   b
0   2021-12-16  0.17
1   2021-12-17  0.17
2   2021-12-18  0.17

I want this df as output

         date   a    b
0   2021-12-15  0.16 NaN
0   2021-12-16  0.16 0.17
1   2021-12-17  0.16 0.17
2   2021-12-18  NaN  0.17

I'm trying to use both concat pd.concat([df1,df2],axis=1 and merge df1.merge(df2,on=['date'] but I'm not able to find a solution

CodePudding user response:

Have a look at pandas merge function.

You want to do:

pd.merge(df1, df2, on='date', how='outer')

This link explains well the different types of merge possible.

CodePudding user response:

Instead of a concat, what you really want to do is an outer merge on the date. So, what you could use is the following :

df = pd.merge(df1,df2,how='outer',on='date')
print(df)

For more info, consult this doc. You'll find plenty of examples and use cases.

  • Related