Str.Contains仅显示True值

时间:2017-12-04 03:48:49

标签: python string pandas contain

我在大型数据帧上使用str.contains,我需要一种方式使str.contains返回我的str.contains函数为True的记录。 (数据帧长达数千行,我正在寻找8个真实的回复)。

谢谢!

aa = filtered_to_df.body.str.contains('AA')

aa.head(10)  
Out[312]:
15864    False  
18040    False  
22576    False  
28092    False  
32800    False  
33236    False   
38027    False  
41222    False  
46647    False  
87645    False  
Name: body, dtype: bool

1 个答案:

答案 0 :(得分:0)

重要区别:str.contains实际上并不过滤您的数据框或系列,它只返回与您应用它的系列相同维度的布尔向量。

例如:如果您有这样的系列:

my_series = pd.Series(['hello world', 'hello', 'world'])

print(my_series)

0    hello world
1          hello
2          world
dtype: object

在此上使用str.contains("hello")将返回一系列大小3,因为它会为系列中的每个单元格提供True / False - 该单元格是否包含单词“hello”?

my_series = pd.Series(['hello world', 'hello', 'world'])

print(my_series.str.contains("hello"))

0     True
1     True
2    False
dtype: bool

要实际过滤数据框或系列,您需要使用切片操作将其环绕。

my_series[my_series.str.contains("hello")]

0    hello world
1          hello
dtype: object