【问题标题】:Python Pandas going through an entire column and checking if it contains a certain strPython Pandas 遍历整个列并检查它是否包含某个 str
【发布时间】:2019-10-23 12:54:52
【问题描述】:

我对 python 数据帧有点陌生,所以这听起来很简单。 我在数据框中有一个名为“body_text”的列,我想查看 body_text 的每一行是否包含“Hello”一词。如果是这样,我想制作另一列,其值为 1 或 0。

我尝试使用str.contains("Hello"),但出现错误,它只选择了具有“Hello”的行并试图将其放入另一列。 我尝试查看其他最终导致更多错误的解决方案 - for 循环和 str in str。

textdf = traindf[['request_title','request_text_edit_aware']]
traindf 是一个巨大的数据框,我只从中提取 2 列

【问题讨论】:

  • 请将您的尝试和错误添加到edit
  • 您好,欢迎来到社区。请记住格式化代码 sn-ps (meta.stackexchange.com/questions/22186/…) 并查看此stackoverflow.com/questions/20109391/… 要正确回答问题,我们需要了解数据框的外观。根据您提供给我们的信息,我们不知道您是否要在多个列中搜索“hello”,我们是否需要在字符串中搜索字符串或仅搜索 hello 等...

标签: python pandas dataframe


【解决方案1】:

如果您的匹配区分大小写,请使用Series.str.contains 并链接.astype 以转换为int

df['contains_hello'] = df['body_text'].str.contains('Hello').astype(int)

如果它应该匹配,不区分大小写,添加 case=False 参数:

df['contains_hello'] = df['body_text'].str.contains('Hello', case=False).astype(int)

更新

如果您需要匹配多个模式,请使用 regex| ('OR') 字符。根据您的要求,您可能还需要一个 '单词边界' 字符。

如果您想了解更多关于regex 模式和字符类的信息,Regexr 是一个很好的资源。

示例

df = pd.DataFrame({'body_text': ['no matches here', 'Hello, this should match', 'high low - dont match', 'oh hi there - match me']})

#                      body_text
#    0           no matches here   
#    1  Hello, this should match   <--  we want to match this 'Hello'
#    2     high low - dont match   <-- 'hi' exists in 'high', but we don't want to match it
#    3    oh hi there - match me   <--  we want to match 'hi' here

df['contains_hello'] = df['body_text'].str.contains(r'Hello|\bhi\b', regex=True).astype(int)

                  body_text  contains_hello
0           no matches here               0
1  Hello, this should match               1
2     high low - dont match               0
3    oh hi there - match me               1

有时,有一个list 要匹配的单词很有用,以便使用python list comprehension 更轻松地创建regex 模式。例如:

match = ['hello', 'hi']    
pat = '|'.join([fr'\b{x}\b' for x in match])
# '\bhello\b|\bhi\b'  -  meaning 'hello' OR 'hi'

df.body_text.str.contains(pat)

【讨论】:

  • 在多个字符的情况下,你会如何实现呢?就像我希望它还包含“Hi”作为要检查的字符串。感谢您的回答!
  • @MeiTei 我已经更新了我的答案,希望对您有所帮助。
【解决方案2】:

使用您在问题中定义的 textdf,尝试:

textdf['new_column'] = [1 if t == 'Hello' else 0 for t in textdf['body_text'] ]

【讨论】:

    【解决方案3】:

    您可以在 Panda 中使用get_dummies() 函数。

    Here 是文档的链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多