python - 查找两个数据帧的两列之间的额外内容 - 相减

标签 python pandas dataframe group-by subtraction

我有 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/

相关文章:

python - 按组滚动总和

PYTHON - 合并日期索引上的两个数据帧

python - 获取中位数对应的索引

python - 如何使用正则表达式或替换来清理列表?

python - 是否有用于临时更改 matplotlib 设置的上下文管理器?

python - 如何根据名称为单个条形着色

python - 计算 Pandas DataFrame 的百分比变化

python - Zlib 在 OS X 中不可用?

python - 从集合中移除 NaN 值

python - S3FS python,凭证内联