how to merge two data frames based on particular column in pandas python?
Question:
I have to merge two dataframes:
df1
company,standard
tata,A1
cts,A2
dell,A3
df2
company,return
tata,71
dell,78
cts,27
hcl,23
I have to unify both dataframes to one dataframe. I need output like:
company,standard,return
tata,A1,71
cts,A2,27
dell,A3,78
Answers:
Use merge
:
print (pd.merge(df1, df2, on='company'))
Sample:
print (df1)
company standard
0 tata A1
1 cts A2
2 dell A3
print (df2)
company return
0 tata 71
1 dell 78
2 cts 27
3 hcl 23
print (pd.merge(df1, df2, on='company'))
company standard return
0 tata A1 71
1 cts A2 27
2 dell A3 78
In order to successfully merge two data frames based on common column(s), the dtype for common column(s) in both data frames must be the same! dtype for a column can be changed by:
df['commonCol'] = df['commonCol'].astype(int)
I think we can also use
df1.merge(df2,on='Company')
I have to merge two dataframes:
df1
company,standard
tata,A1
cts,A2
dell,A3
df2
company,return
tata,71
dell,78
cts,27
hcl,23
I have to unify both dataframes to one dataframe. I need output like:
company,standard,return
tata,A1,71
cts,A2,27
dell,A3,78
Use merge
:
print (pd.merge(df1, df2, on='company'))
Sample:
print (df1)
company standard
0 tata A1
1 cts A2
2 dell A3
print (df2)
company return
0 tata 71
1 dell 78
2 cts 27
3 hcl 23
print (pd.merge(df1, df2, on='company'))
company standard return
0 tata A1 71
1 cts A2 27
2 dell A3 78
In order to successfully merge two data frames based on common column(s), the dtype for common column(s) in both data frames must be the same! dtype for a column can be changed by:
df['commonCol'] = df['commonCol'].astype(int)
I think we can also use
df1.merge(df2,on='Company')