Python 查找两个数据帧的两列之间的附加项-减法
我有两个数据帧(df_a和df_b),有两列:“Animal”和“Name” 在更大的数据框中,同一类型的动物比另一类型的动物多。我如何通过名称找到相同类型的额外动物即(df_a-df_b) 数据帧APython 查找两个数据帧的两列之间的附加项-减法,python,pandas,dataframe,group-by,subtraction,Python,Pandas,Dataframe,Group By,Subtraction,我有两个数据帧(df_a和df_b),有两列:“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
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',这是有意义的,因为它们是字符串而不是数字。还有其他方法吗?您正在寻找一个只剩下
的合并
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
有人告诉我,朋友不会让朋友连络电话。您可能希望将其更改为.loc
类似于merged.loc[merged[''u merge']=='left\u only',['Animal','Name']
。同样重要的是要注意这个答案的灵活性,你可以使用'right\u only'
和'both'
分别从df\u b
或两者中获取值。我没有得到你的的“朋友不要让朋友连锁呼叫”
位。什么意思?如果您认为答案是灵活的,您可以向上投票:(@EricEdLohmarIt通常不适合引用数据帧的一部分,如df['column']['row']
至少部分是因为它可能返回数据的副本,也可能不返回数据的视图。.loc
和.iloc
应该用于在需要调用多个维度时从数据帧中获取数据。不过,在分配和不查询数据时,这确实是一个更大的问题。有趣的是,以前没有看到过这一点:)@user3483203仅适用于字符串,更常见的方法是应用元组,然后使用isin