【问题标题】:How to compare two dataframes based on certain column values and remove them in pandas如何根据某些列值比较两个数据框并在熊猫中删除它们
【发布时间】:2018-07-16 16:42:10
【问题描述】:

我有两个数据框。

df1:

userID    ID    Sex   Date   Month    Year   Security
  John    45   Male     31      03    1975        Low
   Tom    22   Male     01      01    1990       High
  Mary    33 Female     23      05    1990     Medium
  Hary    56   Male     15      09    1970       High

df2:

userID    ID    Sex   Date   Month    Year
  Hari    45   Male     31      03    1975
  Luka    22   Male     01      01    1990
 Johan    33 Female     23      05    1990
 Irfan    56   Male     29      09    1971
  John    45   Male     31      03    1975
   Tom    22   Male     01      01    1990
  Mary    34 Female     34      05    1980
  Hary    56   Male     15      09    1970

我想将 df2 与 df1 进行比较,并仅保留 df2 中具有 列中的常用值 (userID,ID,Date,Month,Year)

所以我的新 df2 应该是这样的:

  John    45   Male     31      03    1975
   Tom    22   Male     01      01    1990
  Hary    56   Male     15      09    1970

在 pandas 中获得此功能的最佳方法是什么? 有人可以帮我吗?

【问题讨论】:

  • 您是否还想比较在Sex 或只是这5 列?

标签: python-3.x pandas


【解决方案1】:

只需简单的merge 跟随dropna

df2.merge(df1,how='left').dropna().drop('Security',1)
Out[318]: 
  userID  ID   Sex  Date  Month  Year
4   John  45  Male    31      3  1975
5    Tom  22  Male     1      1  1990
7   Hary  56  Male    15      9  1970

【讨论】:

    【解决方案2】:

    定义要合并的键列,然后在df2df1的键列之间进行内部合并。 merge 的默认值是内部的,因此您不需要显式指定它。仅将 df1 子集到这些关键列可确保您不会通过合并将其任何列带到 df2

    key_cols = ['userID', 'ID', 'Date', 'Month', 'Year']
    df2.merge(df1.loc[:, df1.columns.isin(key_cols)])
    

    输出:

      userID  ID   Sex  Date  Month  Year
    0   John  45  Male    31      3  1975
    1    Tom  22  Male     1      1  1990
    2   Hary  56  Male    15      9  1970
    

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多