从正则表达式模式返回不匹配的行 [英] Return the unmatched rows from the regex pattern

查看:241
本文介绍了从正则表达式模式返回不匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的熊猫数据框看起来像这样:

If I have a pandas dataframe that looks like this:

      Sequence     Rating
 0    HYHIVQKF     1
 1    YGEIFEKF     2
 2    TYGGSWKF     3
 3    YLESFYKF     4
 4    YYNTAVKL     5
 5    WPDVIHSF     6

这是我使用的代码,返回与以下模式匹配的行: \b.[YF]\w+[LFI]\b

This is the code that I am using the return the rows that match the following pattern: \b.[YF]\w+[LFI]\b

pat = r'\b.[YF]\w+[LFI]\b'
new_df.Sequence.str.contains(pat)

new_df[new_df.Sequence.str.contains(pat)]

上面的代码返回的是与模式匹配的行,但是我可以用什么来返回不匹配的行呢?

The above code is returning the rows that match the pattern, but what can I use to return the unmatched rows?

预期输出:

     Sequence  Rating
1    YGEIFEKF   2
3    YLESFYKF   4
5    WPDVIHSF   6

推荐答案

您可以对现有的布尔序列取反:

You can just do a negation of your existing Boolean series:

df[~df.Sequence.str.contains(pat)]

这将为您提供所需的输出:

This will give you the desired output:

   Sequence  Rating
1  YGEIFEKF       2
3  YLESFYKF       4
5  WPDVIHSF       6

简要说明:

df.Sequence.str.contains(pat)

将返回一个布尔序列:

0     True
1    False
2     True
3    False
4     True
5    False
Name: Sequence, dtype: bool

使用~否定它会产生

~df.Sequence.str.contains(pat)

0    False
1     True
2    False
3     True
4    False
5     True
Name: Sequence, dtype: bool

这是另一个布尔系列,您可以将其传递到原始数据框.

which is another Boolean series you can pass to your original dataframe.

这篇关于从正则表达式模式返回不匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆