I have two data frames with same column but different values, out of which some are same and some are different. I want to compare both columns and keep the common values.
df1
:
A B C
1 1 1
2 4 6
3 7 9
4 9 0
6 0 1
df2
:
A D E
1 5 7
5 6 9
2 3 5
7 6 8
3 7 0
This is what I am expecting after comparison
df2
:
A D E
1 5 7
2 3 5
3 7 0
You can use pd.Index.intersection()
to find the matching columns and do a inner merge finally reindex()
to keep df2.columns
:
match=df2.columns.intersection(df1.columns).tolist() #finds matching cols in both df
df2.merge(df1,on=match).reindex(df2.columns,axis=1) #merge and reindex to df2.columns
A D E
0 1 5 7
1 2 3 5
2 3 7 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.