【问题标题】:How to remove all rows from one dataframe that are part of another dataframe? [duplicate]如何从一个数据框中删除属于另一个数据框的所有行? [复制]
【发布时间】:2020-07-09 10:25:19
【问题描述】:

我有两个这样的数据框

import pandas as pd

df1 = pd.DataFrame(
    {
        'A': list('abcaewar'),
        'B': list('ghjglmgb'),
        'C': list('lkjlytle'),
        'ignore': ['stuff'] * 8
    }
)

df2 = pd.DataFrame(
    {
        'A': list('abfu'),
        'B': list('ghio'),
        'C': list('lkqw'),
        'stuff': ['ignore'] * 4
    }
)

我想删除df1 中的所有行,其中ABCdf2 中的值相同,因此在上述情况下,预期结果是

   A  B  C ignore
0  c  j  j  stuff
1  e  l  y  stuff
2  w  m  t  stuff
3  r  b  e  stuff

实现这一目标的一种方法是

comp_columns = ['A', 'B', 'C']
df1 = df1.set_index(comp_columns)
df2 = df2.set_index(comp_columns)

keep_ind = [
    ind for ind in df1.index if ind not in df2.index
]

new_df1 = df1.loc[keep_ind].reset_index()

有没有人看到一种更直接的方法来避免reset_index() 操作和循环来识别非重叠索引,例如通过市场的掩蔽方式?理想情况下,我不必对列进行硬编码,但可以在上面的列表中定义它们,因为我有时需要 2 个、有时 3 个或有时 4 个或更多列来删除。

【问题讨论】:

  • here
  • @Erfan:谢谢。我可以猜到它已经在那里了,但是在谷歌搜索时错过了......
  • 嗯,找到这些具体问题并不总是那么容易。

标签: python pandas


【解决方案1】:

使用DataFrame.merge 和可选参数indicator=True,然后使用布尔掩码过滤df1 中的行:

df3 = df1.merge(df2[['A', 'B', 'C']], on=['A', 'B', 'C'], indicator=True, how='left')
df3 = df3[df3.pop('_merge').eq('left_only')]

结果:

# print(df3)

   A  B  C ignore
2  c  j  j  stuff
4  e  l  y  stuff
5  w  m  t  stuff
7  r  b  e  stuff

【讨论】:

  • 非常优雅,谢谢(赞成);不知道indicator,这个很方便...
猜你喜欢
  • 2022-11-15
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2016-09-15
  • 1970-01-01
  • 2013-06-24
相关资源
最近更新 更多