python计数一个字符串在大 pandas 数据帧的整个行中出现的次数 [英] python count how many times a string is present in the entire row of a pandas dataframe
本文介绍了python计数一个字符串在大 pandas 数据帧的整个行中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基于之前的问题的问题 .下面的代码运行良好,它告诉我search_string
是否存在于整行中.如何修改最后一行,以便为我提供匹配计数而不是1或0?例如,对于第一行,它应该返回4,因为我的search_string
存在于该行的4个位置.
I have a question based upon my earlier question. Below code runs fine and it tells me whether the search_string
is present in the entire row or not. How could I modify the last line so that it provides me counts of matches instead of 1 or 0? For example, for the first row it should return 4 as my search_string
is present in 4 locations in that row.
sales = [{'account': 'Jones LLC jones', 'Jan': '150', 'Feb': '200', 'Mar': '140 jones jones'},
{'account': 'Alpha Co', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
{'account': 'Blue Inc', 'Jan': '50', 'Feb': '90', 'Mar': '95' }]
df = pd.DataFrame(sales)
df
search_string = 'Jones'
(df.apply(lambda x: x.str.contains(search_string))
.sum(axis=1).astype(int))
推荐答案
您可以使用findall
和.str.len
:
sales = [{'account': 'Jones LLC jones', 'Jan': '150', 'Feb': '200', 'Mar': '140 jones jones'},
{'account': 'Alpha Co', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
{'account': 'Blue Inc', 'Jan': '50', 'Feb': '90', 'Mar': '95' }]
df = pd.DataFrame(sales)
df
search_string = 'jones' #Note changed to lowercase j to find more data.
(df.apply(lambda x: x.str.findall(search_string).str.len())
.sum(axis=1).astype(int))
输出:
0 3
1 0
2 0
dtype: int32
将@Vaishali编辑添加到解决方案中:
Add @Vaishali edit to solution:
df.apply(lambda x: x.str.lower().str.findall(search_string).str.len()).sum(axis=1).astype(int)
输出:
0 4
1 1
2 0
dtype: int32
这篇关于python计数一个字符串在大 pandas 数据帧的整个行中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文