ahmedaao
ahmedaao

Reputation: 397

How to merge two dataframes with pandas Python

here are 2 dataframes :

d1 = pd.DataFrame({'a': [19, 65, 7, 49, 66, 89, 545],
                  'b': [4, 6, 6, 90, 5, 77, 767],
                  'c': [34, 78, 65, 666, '', '', '']})

d2 = pd.DataFrame({'c': [34, 78, 65, '', ''],
                  'd': [4, 6, 6, 90, 767]})

I would like to make a merge between them with "c" column as jointure.

In my case, I use this :

df = pd.merge(d1, d2, how='left')

But the result is not good. In fact, I have some doublons, plus the final result should be a dataframe with the same length of d1. In my case It is not true.

Here is the result I would like to have :

df = pd.DataFrame({'a': [19, 65, 7, 49, 66, 89, 545],
                  'b': [4, 6, 6, 90, 5, 77, 767],
                  'c': [34, 78, 65, 666, '', '', ''],
                  'd': [4, 6, 6, 90, 767, '', '']})

Upvotes: 0

Views: 61

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24322

IIUC:

use concat() and fillna():

df=pd.concat([d1,d2.pop('d')],axis=1).fillna('')
#OR
df=pd.concat([d1,d2['d']],axis=1).fillna('')

Now If you print df you will get your expected output

Upvotes: 2

Related Questions