我有 2 个数据框(df_a 和 df_b),有 2 列:“动物”和“名称”。
在更大的数据框中,相同类型的动物比其他动物更多。如何按名称找到相同类型的额外动物? 即(df_a - df_b)
数据框A
Animal Name
dog john
dog henry
dog betty
dog smith
cat charlie
fish tango
lion foxtrot
lion lima
数据框 B
Animal Name
dog john
cat charlie
dog betty
fish tango
lion foxtrot
dog smith
在这种情况下,额外的内容是:
Animal Name
dog henry
lion lima
尝试:我尝试使用
df_c = df_a.subtract(df_b, axis='columns')
但出现以下错误“-: 'unicode' 和 'unicode' 不支持的操作数类型”,这是有道理的,因为它们是字符串而不是数字。还有其他办法吗?
最佳答案
您正在寻找left_only
合并。
merged = pd.merge(df_a,df_b, how='outer', indicator=True)
merged.loc[merged['_merge'] == 'left_only'][['Animal', 'Name']]
输出
Animal Name
1 dog henry
7 lion lima
说明:
merged = pd.merge(df_a,df_b, how='outer', indicator=True)
给予:
Animal Name _merge
0 dog john both
1 dog henry left_only
2 dog betty both
3 dog smith both
4 cat charlie both
5 fish tango both
6 lion foxtrot both
7 lion lima left_only
额外的动物仅在df_a
中,用left_only
表示。
关于python - 查找两个数据帧的两列之间的额外内容 - 相减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51620658/