pandas中`Series.str.contains("|")`和`Series.apply(lambda x:"|"in x)`之间的区别?

Rac*_*fer 6 python pandas

这是用于测试的代码:

import numpy as np # maybe you should download the package
import pandas as pd # maybe you should download the package
data = ['Romance|Fantasy|Family|Drama', 'War|Adventure|Science Fiction',
       'Action|Family|Science Fiction|Adventure|Mystery', 'Action|Drama',
       'Action|Drama|Thriller', 'Drama|Romance', 'Comedy|Drama', 'Action',
       'Comedy', 'Crime|Comedy|Action|Adventure',
       'Drama|Thriller|History', 'Action|Science Fiction|Thriller']

a = pd.Series(data)
print(a.str.contains("|"))
print(a.apply(lambda x:"|" in x))
print(a)
Run Code Online (Sandbox Code Playgroud)

执行上面的代码后,您将获得以下三个输出:

0     True
1     True
2     True
3     True
4     True
5     True
6     True
7     True
8     True
9     True
10    True
11    True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

print(a.apply(lambda x:"|" in x)) 输出是:

0      True
1      True
2      True
3      True
4      True
5      True
6      True
7     False
8     False
9      True
10     True
11     True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

print(a) 输出是:

image.png

你会看到in 78in Series a没有|.然而,归来print(a.str.contains("|"))就是全部True.这有什么不对?

Max*_*axU 9

|在RegEx中有特殊含义,所以你需要逃避它:

In [2]: a.str.contains(r"\|")
Out[2]:
0      True
1      True
2      True
3      True
4      True
5      True
6      True
7     False
8     False
9      True
10     True
11     True
dtype: bool
Run Code Online (Sandbox Code Playgroud)