在两个数据框的两列之间查找额外内容 - 减去
Find extras between two columns of two dataframes - subtract
我有 2 个数据框(df_a 和 df_b),有 2 列:'Animal' 和 'Name'。
在更大的数据框中,同一类型的动物比其他动物多。我如何通过名称找到相同类型的额外动物? 即(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')
但出现以下错误 "unsupported operand type(s) for -: 'unicode' and '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
表示。
使用isin
df1[~df1.sum(1).isin(df2.sum(1))]
Out[611]:
Animal Name
1 dog henry
7 lion lima
我有 2 个数据框(df_a 和 df_b),有 2 列:'Animal' 和 'Name'。
在更大的数据框中,同一类型的动物比其他动物多。我如何通过名称找到相同类型的额外动物? 即(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')
但出现以下错误 "unsupported operand type(s) for -: 'unicode' and '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
表示。
使用isin
df1[~df1.sum(1).isin(df2.sum(1))]
Out[611]:
Animal Name
1 dog henry
7 lion lima