我有两个熊猫数据帧,它们有一些相同的行。

假设dataframe2是dataframe1的子集。

我怎么能得到dataframe1的行不在dataframe2?

df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14]}) 
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12]})

df1

   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14

df2

   col1  col2
0     1    10
1     2    11
2     3    12

预期结果:

   col1  col2
3     4    13
4     5    14

当前回答

你可以使用isin(dict)方法:

In [74]: df1[~df1.isin(df2.to_dict('l')).all(1)]
Out[74]:
   col1  col2
3     4    13
4     5    14

解释:

In [75]: df2.to_dict('l')
Out[75]: {'col1': [1, 2, 3], 'col2': [10, 11, 12]}

In [76]: df1.isin(df2.to_dict('l'))
Out[76]:
    col1   col2
0   True   True
1   True   True
2   True   True
3  False  False
4  False  False

In [77]: df1.isin(df2.to_dict('l')).all(1)
Out[77]:
0     True
1     True
2     True
3    False
4    False
dtype: bool

其他回答

你可以使用isin(dict)方法:

In [74]: df1[~df1.isin(df2.to_dict('l')).all(1)]
Out[74]:
   col1  col2
3     4    13
4     5    14

解释:

In [75]: df2.to_dict('l')
Out[75]: {'col1': [1, 2, 3], 'col2': [10, 11, 12]}

In [76]: df1.isin(df2.to_dict('l'))
Out[76]:
    col1   col2
0   True   True
1   True   True
2   True   True
3  False  False
4  False  False

In [77]: df1.isin(df2.to_dict('l')).all(1)
Out[77]:
0     True
1     True
2     True
3    False
4    False
dtype: bool

使用merge函数提取不同的行

df = df1.merge(df2.drop_duplicates(), on=['col1','col2'], 
               how='left', indicator=True)

在CSV中保存不同的行

df[df['_merge'] == 'left_only'].to_csv('output.csv')

如前所述,isin要求列和索引必须相同才能进行匹配。如果match只适用于行内容,一种获取掩码的方法是将行转换为(Multi)Index:

In [77]: df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5, 3], 'col2' : [10, 11, 12, 13, 14, 10]})
In [78]: df2 = pandas.DataFrame(data = {'col1' : [1, 3, 4], 'col2' : [10, 12, 13]})
In [79]: df1.loc[~df1.set_index(list(df1.columns)).index.isin(df2.set_index(list(df2.columns)).index)]
Out[79]:
   col1  col2
1     2    11
4     5    14
5     3    10

如果需要考虑索引,set_index有关键字参数append来将列追加到现有索引。如果列没有对齐,list(df.columns)可以替换为列规范以对齐数据。

pandas.MultiIndex.from_tuples(df<N>.to_records(index = False).tolist())

也可以用来创建指数,但我怀疑这是否更有效。

我认为那些包含合并的答案是极其缓慢的。因此,我建议另一种方法来获得两个数据框架之间不同的行:

df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14]}) 
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12]})

免责声明:如果您对两个数据框架不同的特定列感兴趣,那么我的解决方案是有效的。如果您只对那些所有列都相等的行感兴趣,则不要使用这种方法。

比方说,col1是一种ID,你只想获取那些不包含在两个数据框架中的行:

ids_in_df2 = df2.col1.unique()
not_found_ids = df[~df['col1'].isin(ids_in_df2 )]

就是这样。你得到的数据框架只包含那些col1在两个数据框架中都不明显的行。

pd。concat([df1, df2]).drop_duplicate (keep=False)将两个dataframe连接在一起,然后删除所有重复的数据,只保留唯一的行。默认情况下,它将保留第一次出现的副本,但设置keep=False将删除所有副本。

请记住,如果您需要比较具有不同名称的列的dataframe,那么在连接数据aframe之前,必须确保列具有相同的名称。

此外,如果数据框架的列顺序不同,也会影响最终结果。