我想比较两个不同长度的pandas DataFrame并识别匹配的索引号.当值匹配时,我想在新列中标记这些值.
df1:
Index Column 1
41660 Apple
41935 Banana
42100 StrawBerry
42599 Pineapple
df2:
Index Column 1
42599 Pineapple
Output:
Index Column 1 'Matching Index?'
41660 Apple
41935 Banana
42100 StrawBerry
42599 Pineapple True
解决方法:
如果这些确实是索引,那么你可以在索引上使用交集:
In [61]:
df1.loc[df1.index.intersection(df2.index), 'flag'] = True
df1
Out[61]:
Column 1 flag
Index
41660 Apple NaN
41935 Banana NaN
42100 StrawBerry NaN
42599 Pineapple True
否则使用isin:
In [63]:
df1.loc[df1['Index'].isin(df2['Index']), 'flag'] = True
df1
Out[63]:
Index Column 1 flag
0 41660 Apple NaN
1 41935 Banana NaN
2 42100 StrawBerry NaN
3 42599 Pineapple True
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。