[英]create another column based on matching of two data frames columns
I have two data frames df1 and df2 with a common column ID.我有两个数据框 df1 和 df2 具有公共列 ID。 Both the data frames have different number of rows and columns.两个数据框都有不同的行数和列数。 I want to compare these two dataframe ID's.我想比较这两个数据帧 ID。 I want to create another column y in df1 and for all the common id's present in df1 and df2 the value of y should be 0 else 1. For example df1 is我想在 df1 中创建另一列 y,对于 df1 和 df2 中存在的所有公共 ID,y 的值应为 0 否则为 1。例如 df1 是
Id col1 col2
1 Abc def
2 Geh ghk
3 Abd fg
1 Dfg abc
And df2 is而 df2 是
Id col3 col4
1 Dgh gjs
2 Gsj aie
The final dataframe should be最终的数据帧应该是
Id col1 col2 y
1 Abc def 0
2 Geh ghk 0
3 Abd fg 1
1 Dfg abc 0
Lets create df1 and df2 first:让我们先创建 df1 和 df2:
df1=pd.DataFrame({'ID':[1,2,3,1], 'col1':['A','B','C', 'D'], 'col2':['C','D','E', 'F']})
df2=pd.DataFrame({'ID':[1,2], 'col3':['AA','BB'], 'col4':['CC','DD']})
Here, pandas lambda function comes handy:在这里,pandas lambda 函数派上用场:
df1['y'] = df1['ID'].map(lambda x:0 if x in df2['ID'].values else 1)
df1
ID col1 col2 y
0 1 A C 0
1 2 B D 0
2 3 C E 1
3 1 D F 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.