大熊猫中的“ Series.str.contains(“ |”)`和Series.apply(lambda x:“ |” in x)之间有何区别?

时间:2018-06-21 16:53:15

标签: 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)

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

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

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

print(a)的输出是:

image.png

您将在7中的8Series a中看到没有|。但是,print(a.str.contains("|"))的返回全部为True。怎么了?

1 个答案:

答案 0 :(得分:9)

| has a special meaning in 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