【问题标题】:Str.Contains show only True valuesStr.Contains 仅显示 True 值
【发布时间】:2018-05-17 11:55:45
【问题描述】:

我在大型数据帧上使用 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

【问题讨论】:

  • 显示您的数据主管
  • 你是如何使用 str.contains 的?
  • 已添加 - 我在想有没有办法在系列中使用 loc?
  • 我刚刚加了:aa = filters_to_df.body.str.contains('AA')
  • 如果你想否定使用波浪号~,比如~aaaa = ~filtered.....

标签: python string pandas contain


【解决方案1】:

重要区别: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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2020-08-17
    • 2023-03-15
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多