【问题标题】:Python 2.7 with Pandas: How does one recover the non intersecting parts of two dataframes?带有 Pandas 的 Python 2.7:如何恢复两个数据帧的不相交部分?
【发布时间】:2014-05-25 02:34:21
【问题描述】:

我有两个数据框,第二个是第一个的子集。我现在如何找到第一个数据帧中不包含在第二个数据帧中的部分?例如:

new_dataframe_1

    A   B   C   D
1   a   b   c   d
2   e   f   g   h
3   i   j   k   l
4   m   n   o   p


new_dataframe_2

    A   B   C   D
1   a   b   c   d
3   i   j   k   l


new_dataframe_3 = not intersection of new_dataframe_1 and new_dataframe_2


    A   B   C   D
2   e   f   g   h
4   m   n   o   p

感谢您的帮助!

编辑:我最初将交叉点称为联合,但后来改变了这一点。

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    嗯,一种方法是使用isin(但您也可以使用merge 命令来实现...我展示了这两种方法的示例)。例如:

    >>> df1
    
       A  B  C  D
    0  a  b  c  d
    1  e  f  g  h
    2  i  j  k  l
    3  m  n  o  p
    
    >>> df2
    
       A  B  C  D
    0  a  b  c  d
    1  i  j  k  l
    
    >>> df1[~df1.isin(df2.to_dict('list')).all(axis=1)]
    
       A  B  C  D
    1  e  f  g  h
    3  m  n  o  p
    

    解释。 isin 可以检查是否使用多列,如果你给它一个字典:

    >>> df2.to_dict('list')
    
    {'A': ['a', 'i'], 'C': ['c', 'k'], 'B': ['b', 'j'], 'D': ['d', 'l']}
    

    然后isin 将创建一个布尔型 df,我可以使用它来选择我们想要的列(在这种情况下,需要所有列匹配,然后与 ~ 取反):

    >>> df1.isin(df2.to_dict('list'))
    
          A      B      C      D
    0   True   True   True   True
    1  False  False  False  False
    2   True   True   True   True
    3  False  False  False  False
    

    在具体示例中,我们不需要向isin 提供数据帧的dict 版本,因为我们只需查看A 列即可识别有效行:

    >>> df1[~df1['A'].isin(df2['A'])]
    
       A  B  C  D
    1  e  f  g  h
    3  m  n  o  p
    

    您也可以使用merge 执行此操作。在子集数据框中创建一个唯一列。合并时,较大数据框中的唯一行将为您创建的列具有 NaN

    >>> df2['test'] = 1
    >>> new = df1.merge(df2,on=['A','B','C','D'],how='left')
    >>> new
    
       A  B  C  D  test
    0  a  b  c  d     1
    1  e  f  g  h   NaN
    2  i  j  k  l     1
    3  m  n  o  p   NaN
    

    所以选择 test == NaN 的行并删除 test 列:

    >>> new[new.test.isnull()].drop('test',axis=1)
    
       A  B  C  D
    1  e  f  g  h
    3  m  n  o  p
    

    编辑:@user3654387 指出,合并方法对于大型数据帧的性能要好得多。

    【讨论】:

    • 太好了,感谢您提供的非常完整的答案,显示了几个选项。感谢您的帮助!
    • 我只是想为其他阅读本文的人添加一些进一步的文档......上面提到的后一种方法比前一种方法对于大数据帧要快得多。我尝试了这两种方法,但在对具有 80,000 行和 5 列的数据框进行排序 10 分钟后没有得到解决方案,但后一种合并方法只需要几秒钟。再次感谢!
    • 感谢@user3654387,我编辑了答案以表明merge 方法的性能更好。
    猜你喜欢
    • 2017-05-28
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多