【问题标题】:Issue Finding Substring问题查找子字符串
【发布时间】:2019-06-30 12:40:50
【问题描述】:

我正在尝试在 df 列中查找子字符串 Chief。在带有空格的文本上使用 split() 可以正常工作,但使用 find() 时无法按预期工作。

sum(df['JobTitle'].apply(lambda x :'chief' in x.lower().split() ))
sum(df['JobTitle'].apply(lambda x :  x.lower().find('chief') ==1))

您能否强调一下find 使用中的问题是什么?

【问题讨论】:

  • .find 返回索引,不管它是否在字符串中。
  • 了解 rassar。谢谢!!

标签: python python-3.x string dataframe


【解决方案1】:

你可以试试re

import re

# if it appears, add 1, else add 0
sum(df['JobTitle'].apply(lambda x : int(bool(re.findall(r'\bchief\b', x.lower()))))

# add the number of times the word appears
sum(df['JobTitle'].apply(lambda x : len(re.findall(r'\bchief\b', x.lower()))) 

编辑 如果你想捕捉chief,而不是里面有酋长的话,比如mischief,使用r'\bchief\b'

演示:https://regex101.com/r/jYOfM1/1

【讨论】:

  • Giving Error : TypeError Traceback (最近一次调用最后一次) in 3 4 import re ----> 5 sum(df['JobTitle'] .apply(lambda x : re.findall(r'chief', x.lower()))) TypeError: +: 'int' and 'list' 不支持的操作数类型
  • sum(df['JobTitle'].apply(lambda x : 0 if re.search(r'chief', x.lower()) is None else 1) 以上 1 工作正常,但我需要了解我在正常查找方法中缺少什么?
  • 谢谢 sashaboulouds,我在下面尝试过,但 re 的问题是它计算额外的单词,其中单个单词不是酋长,但包含酋长,恶作剧等 sum(df['JobTitle'].apply(lambda x : 0 if len(re.findall(r'chief', x.lower()))==0 else 1))
  • edited我的回答,如果解决了,请通知解决
  • 我做了,但似乎因为我的声誉很低,它不会加起来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
  • 2012-09-07
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多