如何缩短Pandas遍历50万行表统计8字母以上单词的循环耗时
Pandas 大文本列单词统计优化方案
原有代码问题梳理
- 自定义
howmany8函数逻辑错误:counter+=counter应该是counter+=1,否则返回值永远为0 newdf.dropna(subset = ['text'])没有重新赋值或添加inplace=True参数,空值删除操作不生效- 逐行遍历修改DataFrame是性能最低的写法,完全没有利用Pandas向量化运算的优势,是50万行数据耗时过长的核心原因
- 最后统计的列名是
words,但实际生成的列是wordssum,列名不匹配会直接报错
优化实现方案
方案1:易读性优先,性能满足绝大多数场景
全部使用Pandas内置向量化操作,避免Python层循环,50万行数据通常3秒内可跑完:
import pandas as pd import re # 过滤text列为空的行 df_clean = df.dropna(subset=['text']).copy() # 拆分单词后统计每行长度超过8的单词数 df_clean['wordssum'] = df_clean['text'].str.split(r'\s', expand=False).apply( lambda words: sum(1 for word in words if len(word) > 8) ) # 汇总得到总数量 total = df_clean['wordssum'].sum() print(total)
方案2:性能最优,比方案1快30%以上
直接用正则匹配所有长度≥9的非空白字符序列,不需要生成中间单词列表,性能更高:
import pandas as pd import re # 预编译正则,匹配长度≥9的连续非空白字符(即长度超过8的单词) pattern = re.compile(r'\S{9,}') df_clean = df.dropna(subset=['text']).copy() # 直接统计每行符合规则的单词数 df_clean['wordssum'] = df_clean['text'].str.count(pattern) total = df_clean['wordssum'].sum() print(total)
内容的提问来源于stack exchange,提问作者Omer Eliyahu
相关产品推荐
相关产品推荐

