[英]Pandas: compare how to compare two columns in different sheets and return matched value
I have two dataframes with multiple columns.我有两个包含多列的数据框。
I would like to compare df1['id'] and df2['id'] and return a new df with another column that have the match value.我想比较 df1['id'] 和 df2['id'] 并返回一个新的 df 与具有匹配值的另一列。 example:
例子:
df1
**id** **Name**
1 1 Paul
2 2 Jean
3 3 Alicia
4 4 Jennifer
df2
**id** **Name**
1 1 Paul
2 6 Jean
3 3 Alicia
4 7 Jennifer
output
**id** **Name** *correct_id*
1 1 Paul 1
2 2 Jean N/A
3 3 Alicia 3
4 4 Jennifer N/A
Note- the length of the two columns I want to match is not the same.注意 - 我要匹配的两列的长度不一样。
Try:尝试:
df1["correct_id"] = (df1["id"].isin(df2["id"]) * df1["id"]).replace(0, "N/A")
print(df1)
Prints:印刷:
id Name correct_id
0 1 Paul 1
1 2 Jean N/A
2 3 Alicia 3
3 4 Jennifer N/A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.