0

I have 3 Data Frames:

first:

Country col1
Afghanistan 6.4
Albania 7.3

sec:

Country col2
Afghanistan 610
Algeria 983

last:

Country col3
Afghanistan 1
Angola 2

And I want to connect them by col "Country" and fill the empty values with np.nan to get:

Country col1 col2 col3
Afghanistan 6.4 601 1
Albania 7.3 NaN NaN
Algeria NaN 983 NaN
Angola NaN NaN 2
Socka
  • 37
  • 5

1 Answers1

0

You can use df.merge() with type outer for this.

import pandas as pd
from functools import reduce

#create dataframes
df1= pd.DataFrame([["Afghanistan", 6.4], ["Albania", 7.4]], columns=['Country', 'col1'])
df2= pd.DataFrame([["Afghanistan", 610], ["Algeria", 983]], columns=['Country', 'col2'])
df3= pd.DataFrame([["Afghanistan", 1], ["Angola", 2]], columns=['Country', 'col3'])

#merge them all on Country
df_merged = reduce(lambda  left,right: pd.merge(left,right,on=['Country'],
                                            how='outer'), [df1, df2, df3])

       Country  col1   col2  col3
0  Afghanistan   6.4  610.0   1.0
1      Albania   7.4    NaN   NaN
2      Algeria   NaN  983.0   NaN
3       Angola   NaN    NaN   2.0
Irfanuddin
  • 2,295
  • 1
  • 15
  • 29