python – 删除pandas DataFrame中的行,其中行包含列表中的字符串?

我知道如何从单列(‘From’)pandas DataFrame中删除行,其中行包含一个字符串,例如给定df和somestring:

df = df[~df.From.str.contains(someString)]

现在我想做类似的事情,但这次我希望删除任何包含另一个列表的任何元素中的字符串的行.如果我不使用熊猫,我会使用和if … not … in approach.但是我如何利用熊猫自己的功能来实现这一目标呢?给定要删除的项目列表忽略这些,从逗号分隔的字符串EMAILS_TO_IGNORE文件中提取,我试过:

with open(EMAILS_TO_IGNORE) as emails:
        ignorethese = emails.read().split(', ')
        df = df[~df.From.isin(ignorethese)]

我是否通过首先将文件分解为列表来卷积问题?鉴于它是逗号分隔值的纯文本文件,我可以通过更简单的方法绕过它吗?

最佳答案
Series.str.contains支持正则表达式,您可以使用|来忽略要忽略的电子邮件列表中的正则表达式OR它们,然后在contains中使用它.示例 –

df[~df.From.str.contains('|'.join(ignorethese))]

演示 –

In [109]: df
Out[109]:
                                         From
0         Grey Caulfu <grey.caulfu@ymail.com>
1  Deren Torculas <deren.e.torcs87@gmail.com>
2    Charlto Youna <youna.charlto4@yahoo.com>

In [110]: ignorelist = ['grey.caulfu@ymail.com','deren.e.torcs87@gmail.com']

In [111]: ignorere = '|'.join(ignorelist)

In [112]: df[~df.From.str.contains(ignorere)]
Out[112]:
                                       From
2  Charlto Youna <youna.charlto4@yahoo.com>

请注意,如the documentation所述,它使用re.search().

点赞