In this python pandas program, we will merge two Dataframes with different columns using the pandas library.
Steps to solve the program
- Import pandas library as pd.
- Create two dataframes using pd.DataFrame().
- Merge two Dataframes with different columns using pd.concat([df1,df2], axis=0, ignore_index=True).
- pd.concat() will merge the two dataframe but by setting the axis=0 and ignore_index=True it will merge two Dataframes with different columns.
- It will show NaN if there is no record of a value in a column.
- Print the output.
import pandas as pd
df1 = pd.DataFrame({'Id':['S1','S2','S3'],
'Name':['Ketan','Yash','Abhishek'],
'Marks':[90,87,77]})
df2 = pd.DataFrame({'Sr.no.':[1,2,3,4],
'Name':['Alex','John','Peter','Klaus'],
'Age':[30,27,29,33]})
print('Dataframe 1: \n',df1)
print('Dataframe 2: \n',df2)
print("Merge two dataframes with different columns:")
result = pd.concat([df1,df2], axis=0, ignore_index=True)
print(result)
Output :
Dataframe 1:
Id Name Marks
0 S1 Ketan 90
1 S2 Yash 87
2 S3 Abhishek 77
Dataframe 2:
Sr.no. Name Age
0 1 Alex 30
1 2 John 27
2 3 Peter 29
3 4 Klaus 33
Merge two dataframes with different columns:
Id Name Marks Sr.no. Age
0 S1 Ketan 90.0 NaN NaN
1 S2 Yash 87.0 NaN NaN
2 S3 Abhishek 77.0 NaN NaN
3 NaN Alex NaN 1.0 30.0
4 NaN John NaN 2.0 27.0
5 NaN Peter NaN 3.0 29.0
6 NaN Klaus NaN 4.0 33.0