【问题标题】:python - how to select difference between two dataframes and it's different columnpython - 如何选择两个数据框之间的差异及其不同的列
【发布时间】:2020-09-07 04:22:32
【问题描述】:

我有两个数据框,df2 是更多列

如果df1中的行在df2中没有,我选择它到df3

df1

    id  colA colB
0   1   4    1
1   2   5    2
2   3   2    4
3   4   4    2
4   5   2    4

df2

    id  colA colB colC
0   1   4    1    0
1   2   5    2    0
2   5   2    4    0

我想从 df1 中选择一些行

df3

    id  colA colB
0   3   2    4
1   4   4    2

【问题讨论】:

  • 好的,那么你的代码在哪里?
  • df3=df1.loc[~df1.id.isin(df2.id),].copy()
  • 你只比较'id'列吗?

标签: python pandas dataframe


【解决方案1】:

使用drop_duplicates:

import pandas as pd

df1 = pd.DataFrame({'id': [1,2,3,4,5],
                    'colA':[4,5,2,4,2],
                    'colB':[1,2,4,2,4]})

df2 = pd.DataFrame({'id': [1,2,5],
                    'colA':[4,5,2],
                    'colB':[1,2,4])

pd.concat([df1,df2]).drop_duplicates(subset='id',keep=False)

输出:

   id    colA   colB
2   3    2     4
3   4    4     2

【讨论】:

    【解决方案2】:

    假设您在 'id' 列上进行比较(如果不是,请澄清),您可以使用带有布尔索引的 Series.isin

    >>> df3 = df1[~df1['id'].isin(df2['id'])]
    >>> df3
       id  colA  colB
    2   3     2     4
    3   4     4     2
    

    【讨论】:

      【解决方案3】:
      df3 = df1.loc[~df1['id'].isin(list(df2['id']))]
      

      输出:

         id  colA  colB
      2   3     2     4
      3   4     4     2
      

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 2020-02-11
        • 2013-05-02
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        • 2021-11-28
        • 2019-12-06
        相关资源
        最近更新 更多