You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为pandas apply调用的preprocessing预处理函数添加进度条?

Pandas apply 操作添加进度条方案

前置优化:降低预处理总耗时

你当前的预处理函数存在重复加载资源的问题,会额外增加运行耗时,先做如下优化,仅初始化一次停用词和词干提取器:

import string
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

# 提前加载资源,仅执行一次
eng_stopwords = stopwords.words('english')
stemmer = PorterStemmer()

def preprocessing(text):
    text = text.lower()
    text = "".join([char for char in text if char not in string.punctuation])
    words = word_tokenize(text)
    words = [word for word in words if word not in eng_stopwords]
    words = [stemmer.stem(word) for word in words]
    return words

接入进度条

使用Python通用进度条库tqdm即可实现pandas apply操作的进度可视化,具体步骤如下:

安装依赖

pip install tqdm

普通终端/脚本场景使用

替换原有apply调用逻辑即可:

from tqdm import tqdm
# 注册pandas进度条扩展,desc参数为进度条前置描述文本,可自定义
tqdm.pandas(desc="处理评论中")
# 替换apply为progress_apply
df['reviewText'] = df['reviewText'].progress_apply(lambda x: preprocessing(x))

运行后会自动在终端输出进度条、已处理条数、每秒处理速度、剩余预估时间等信息。

Jupyter Notebook/Lab场景使用

导入适配Jupyter的tqdm模块即可获得交互型进度条:

from tqdm.notebook import tqdm
# 注册pandas进度条扩展,desc参数为进度条前置描述文本,可自定义
tqdm.pandas(desc="处理评论中")
# 替换apply为progress_apply
df['reviewText'] = df['reviewText'].progress_apply(lambda x: preprocessing(x))

内容的提问来源于stack exchange,提问作者Sticky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 20:06:03