【问题标题】:Python: compare dataframes based on two conditionsPython:根据两个条件比较数据帧
【发布时间】:2017-09-01 11:55:01
【问题描述】:

我有以下两个数据框:

df1:

date   id 
2000   1
2001   1
2002   2

df2:

date   id 
2000   1
2002   2

我现在想根据日期和 id 提取 df1 中但不在 df2 中的观察列表。

结果应该是这样的:

date id
2001  1

我知道如何使用 isin 将列与列表进行比较,如下所示:

result = df1[~df1["id"].isin(df2["id"].tolist())]

但是,这只会根据列 ID 比较两个数据框。因为它可能是 id 在 df1 和 df2 中,但对于不同的日期,重要的是我只获得两个数据帧中同时存在的值 - id 和 date - 。有人知道怎么做吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用merge

    In [795]: (df1.merge(df2, how='left', indicator='_a')
                  .query('_a == "left_only"')
                  .drop('_a', 1))
    Out[795]:
       date  id
    1  2001   1
    

    详情

    In [796]: df1.merge(df2, how='left', indicator='_a')
    Out[796]:
       date  id         _a
    0  2000   1       both
    1  2001   1  left_only
    2  2002   2       both
    
    In [797]: df1.merge(df2, how='left', indicator='_a').query('_a == "left_only"')
    Out[797]:
       date  id         _a
    1  2001   1  left_only
    

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 1970-01-01
      • 2019-07-21
      • 2021-09-08
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多