string.contains的逆转在python,pandas中

Xod*_*777 27 python csv string python-2.7 pandas

我的代码中有类似的东西:

df2 = df[df['A'].str.contains("Hello|World")]

但是,我想要所有包含Hello或World的行.我如何最有效地扭转这一局面?

DSM*_*DSM 34

您可以使用代字号~来翻转bool值:

>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
>>> df.A.str.contains("Hello|World")
0     True
1    False
2     True
3    False
Name: A, dtype: bool
>>> ~df.A.str.contains("Hello|World")
0    False
1     True
2    False
3     True
Name: A, dtype: bool
>>> df[~df.A.str.contains("Hello|World")]
       A
1   this
3  apple

[2 rows x 1 columns]
Run Code Online (Sandbox Code Playgroud)

这是否是最有效的方式,我不知道; 你必须把它与其他选择时间对准.有时候使用正则表达式比较慢df[~(df.A.str.contains("Hello") | (df.A.str.contains("World")))],但是我很难猜测交叉的位置.


Mar*_*ers 7

.contains()方法使用正则表达式,因此您可以使用负前瞻测试来确定包含单词:

df['A'].str.contains(r'^(?:(?!Hello|World).)*$')
Run Code Online (Sandbox Code Playgroud)

这种表达的哪里话任何字符串匹配HelloWorld字符串中随处可见.

演示:

>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
>>> df['A'].str.contains(r'^(?:(?!Hello|World).)*$')
0    False
1     True
2    False
3     True
Name: A, dtype: bool
>>> df[df['A'].str.contains(r'^(?:(?!Hello|World).)*$')]
       A
1   this
3  apple
Run Code Online (Sandbox Code Playgroud)