【发布时间】:2018-01-22 03:57:54
【问题描述】:
我有下面的代码在整行中搜索给定的单词。代码来自我之前的question。目前,python 搜索行中给定单词的出现。但我只想找到完整的单词。
当python搜索'jo'时,它不应该返回任何结果,因为没有单词'jo',但是当搜索'jones'时,python应该在第一行返回5
1) 我应该如何修改我的搜索?我知道我必须使用正则表达式。但我不确定如何实现它。
我试过findall((?i)\bsearch_string\b),但出错了
2) 如果任何列的数据类型为浮点数,则下面的代码会给出错误。为了克服这个问题,我将我的原始数据框拆分为非数字和数字列,在代码下方运行,然后将数字列连接回来。有没有一种优雅的方式来做同样的事情
sales = [{'account': 'jones', 'Jan': '150 jones', 'Feb': '200 jones', 'Mar': '140 jones jones'},
{'account': '1', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
{'account': '1', 'Jan': '50', 'Feb': '90', 'Mar': '95' }]
df = pd.DataFrame(sales)
df
df_list = []
search_string='jones'
for search_string in ['jo', 'jones']:
#use above method but rename the series instead of setting to
# a columns. The append to a list.
df_list.append(df.apply(lambda x: x.str.lower().str.findall(search_string).str.len()).sum(axis=1).astype(int).rename(search_string))
#concatenate the list of series into a DataFrame with the original df
df = pd.concat([df] + df_list, axis=1)
df
#
使用下面给出的答案的更新代码
sales = [{'account': 'jones.', 'Jan': '150 jones', 'Feb': '200 .jones', 'Mar': '140 jones jones'},
{'account': '1', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
{'account': '1', 'Jan': '50', 'Feb': '90', 'Mar': '95' }]
df = pd.DataFrame(sales)
df
df_list = []
search_string='jones'
for search_string in ['jones.', 'jone','jones']:
#use above method but rename the series instead of setting to
# a columns. The append to a list.
df_list.append(df.apply(lambda x: x.str.lower().str.findall(r'\b{0}\b'.format(search_string)).str.len()).sum(axis=1).astype(int).rename(search_string))
#concatenate the list of series into a DataFrame with the original df
df = pd.concat([df] + df_list, axis=1)
df
【问题讨论】: