【问题标题】:Find Difference between 2 dataframes查找 2 个数据帧之间的差异
【发布时间】:2021-07-17 08:42:02
【问题描述】:

我是 pandas 的新手,有一个问题。我有 2 个数据框:

df1 = pd.DataFrame({'ID': ['ID1', 'ID2', 'ID3', 'ID6'],
                 'Value': ['59', '29', '73', '34']})

df2 = pd.DataFrame({'ID': ['ID1', 'ID2', 'ID4'],
                     'Value': ['54', '29', '73']})

我想获得一个输出数据框,其中列出了更改的值 (ID1) 以及 df1 和 df2 中的各个 ID(如 ID3、ID4 和 ID6)

提前非常感谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    进行外部合并并计算差异:

    out=df1.merge(df2,on='ID',how='outer')
    out['Difference']=out.pop('Value_x').astype(float)-out.pop('Value_y').astype(float)
    

    out的输出:

       ID   Difference
    0   ID1     5.0
    1   ID2     0.0
    2   ID3     NaN
    3   ID6     NaN
    4   ID4     NaN
    

    或

    合并后使用 0 填充 NaN:

    out=df1.merge(df2,on='ID',how='outer').fillna(0)
    out['Difference']=out.pop('Value_x').astype(float)-out.pop('Value_y').astype(float)
    

    out的输出:

        ID  Difference
    0   ID1     5.0
    1   ID2     0.0
    2   ID3     73.0
    3   ID6     34.0
    4   ID4     -73.0
    

    【讨论】:

      【解决方案2】:
      changed = set()
      individual = (set(df1['ID'].to_numpy()) - set(df2['ID'].to_numpy())).union(set(df2['ID'].to_numpy()) - set(df1['ID'].to_numpy()))
      for i in set(df1['ID'].to_numpy()) - (set(df1['ID'].to_numpy()) - set(df2['ID'].to_numpy())):
          if not df1[df1['ID'] == i]['Value'].equals(df2[df2['ID'] == i]['Value']):
              changed.add(i)
      print(changed, individual)
      >>> {'ID1'} {'ID6', 'ID3', 'ID4'}
      

      【讨论】:

        猜你喜欢
        • 2018-07-16
        • 1970-01-01
        • 2019-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多