python计算一个字符串在pandas数据帧的整行中出现的次数 [英] python count how many times a string is present in the entire row of a pandas dataframe

查看:41
本文介绍了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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆