如何在这个函数中添加进度条?

  • 本文关键字:添加 函数 python pandas
  • 更新时间 :
  • 英文 :


我有一个这样的文本预处理函数:

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 stopwords.words('english')]
words = [PorterStemmer().stem(word) for word in words]

return words

我将在这个函数中像这样传递一个数据帧:

df['reviewText'] = df['reviewText'].apply(lambda x: preprocessing(x))

但是dataframe列有大约10000个评论句子,代码需要花费太多时间来完成。有没有办法增加一个"进度条",这样我就会对时间有一些了解。

p。如果您想在本地机器上尝试,可以在此站点找到相关数据。

导入TQDM,将.apply()替换为.progress_apply():

from tqdm.auto import tqdm
tqdm.pandas()
df['reviewText'] = df['reviewText'].progress_apply(lambda x: preprocessing(x))

如果你想要一个进度条,你可以让有一个循环:按照定义,进度条就是一个循环。幸运的是,你在apply这里有一个。在不停止使用apply的情况下,作为一个非常快速的简单解决方案,我将使用更新进度条的函数作为副作用:

from tqdm import tqdm
t = tqdm(total=len(df.index))
def fn(x, state=[0]):
preprocessing(x)
state[0] += 1
t.update(state[0])
df['reviewText'] = df['reviewText'].apply(fn)
t.close()

这是否比显式地写出循环更清楚,这是你的调用;我不确定。

(state=[0]怎么了?)我们为fn定义了一个可变变量kwarg,它只分配一次,然后使用它来跟踪状态,因为使用这种方法我们必须手动管理状态。

显式循环
applied = []
for row in tqdm(df["reviewText"]):
applied.append(preprocessing(row)
df["reviewText"] = applied

最新更新