如何统计DataFrame列中指定字符串的最大连续出现次数
统计Pandas DataFrame中特定字符串的最大连续出现次数
这个需求其实挺常见的,用Pandas的序列操作和分组技巧就能轻松搞定,我给你两种实用方案,附代码和详细解释:
方法一:通用分组统计法
先还原你的示例DataFrame:
import pandas as pd # 构造示例数据 df = pd.DataFrame({ 'col1': ['string1', 'string1', 'string1', 'string2', 'string3', 'string3', 'string1'] })
接下来定义一个可复用的函数,核心思路是先给连续相同的字符串打上「组标签」,再统计每个组的长度:
def get_max_consecutive(df, col_name, target): # 生成连续分组ID:当前行与上一行内容不同时,组ID自动+1 group_ids = df[col_name].ne(df[col_name].shift()).cumsum() # 按组ID和列值分组,计算每组的行数(即连续出现次数) count_by_group = df.groupby([group_ids, col_name]).size() # 筛选目标字符串的所有组,取最大次数;如果没有目标字符串则返回0 return count_by_group.get((slice(None), target), pd.Series([0])).max()
测试一下效果:
print(get_max_consecutive(df, 'col1', 'string1')) # 输出3,和预期一致 print(get_max_consecutive(df, 'col1', 'string3')) # 输出2,完全正确 print(get_max_consecutive(df, 'col1', 'string4')) # 输出0,优雅处理不存在的情况
方法二:先筛选再分组(更高效)
如果你的DataFrame数据量很大,先筛选出目标字符串的行再分组,能大幅减少计算量:
def get_max_consecutive_fast(df, col_name, target): # 先筛选出等于目标字符串的行 target_mask = df[col_name] == target # 给连续的目标字符串打组标签 consecutive_groups = target_mask.ne(target_mask.shift()).cumsum() # 统计每个连续组的大小,取最大值;没有目标字符串则返回0 return consecutive_groups[target_mask].value_counts().max() if target_mask.any() else 0
测试结果和方法一完全一致,但处理大数据集时速度会明显更快。
关键逻辑拆解
ne()是Pandas中「不等于」的缩写,配合shift()可以快速检测连续行的内容变化,找到新组的起始点。cumsum()把布尔值(True=1,False=0)累加,生成唯一的组ID,连续相同的字符串会被分到同一个组。value_counts()或groupby().size()用来统计每个组的长度,也就是对应字符串的连续出现次数。
内容的提问来源于stack exchange,提问作者Sd Junk
相关产品推荐
相关产品推荐

