【问题标题】:Subtract two non-numeric dataframes in python pandas [duplicate]在python pandas中减去两个非数字数据框[重复]
【发布时间】:2023-03-06 08:49:01
【问题描述】:

我有两个数据框,列名相同。我想从另一个中减去一个。所以 A-B 应该给我 A 中的内容,但 B 中没有。所以 A 减去 A 和 B 的交集。如下图所示。

代码:

import pandas as pd
df1 = pd.DataFrame(columns=['A','B','C'])
df2 = pd.DataFrame(columns=['A','B','C'])
df1 = df1.append({'A': 'bmw','B':'three','C':'series'}, ignore_index=True)
df1 = df1.append({'A': 'merc','B':'S','C':'class'}, ignore_index=True)
df1 = df1.append({'A': 'Audi','B':'A','C':'eight'}, ignore_index=True)

df2 = df2.append({'A': 'merc','B':'ccc','C':'sss'}, ignore_index=True)
print(df1)
print(df2)
print(pd.merge(df1,df2,how='left'))

我期望的结果是:

{'A': 'bmw','B':'three','C':'series'} 
{'A': 'Audi','B':'A','C':'eight'}

但是我得到了

{'A': 'merc','B':'ccc','C':'sss'}

【问题讨论】:

    标签: python pandas dataframe merge subtraction


    【解决方案1】:

    您只需删除df1['A'] 在整个df2['A'] 系列中的行。

    res = df1.loc[~df1['A'].isin(df2['A'])]
    
    print(res)
    
    #       A      B       C
    # 0   bmw  three  series
    # 2  Audi      A   eight
    

    【讨论】:

    • 昨天被骗了:(
    • 将作为社区 wiki 离开以帮助该人
    • @jpp 我没有“键”列,三列(A、B、C)应该是键。这就是它与原始问题的不同之处
    猜你喜欢
    • 2022-01-08
    • 2019-02-27
    • 1970-01-01
    • 2015-04-22
    • 2017-12-16
    • 2017-04-15
    • 2023-04-11
    • 2020-04-26
    • 2021-11-08
    相关资源
    最近更新 更多