如何在pandas apply中使用tqdm?

6

Tqdm文档展示了一个tqdm在pandas apply中使用progress_apply的例子。我从这里 https://tqdm.github.io/docs/tqdm/ 改编了以下代码,用于一个常常需要几分钟执行(func1是一个正则表达式函数)的流程。

from tqdm import tqdm
tqdm.pandas()
df.progress_apply(lambda x: func1(x.textbody), axis=1)

生成的进度条没有显示任何进度。当循环开始时,它只会从0跳到100,表示循环已经完成。我目前正在运行的是tqdm版本4.61.2


这个回答解决了你的问题吗?https://dev59.com/JWMl5IYBdhLWcg3wMkko - Matthew Borish
我已经尝试过那篇帖子中的解决方案了,但对我无效。 - Fanylion
你能否提供一个最小可重现的代码和数据示例? - Matthew Borish
1个回答

14

如何在pandas中使用tqdm

通常情况下,在列或行上执行操作时,人们倾向于使用lambda表达式。 这可以通过多种方式完成。

  • 请注意:如果您在jupyter笔记本中工作,则应使用tqdm_notebook而不是tqdm。
  • 另外,我不确定您的代码长什么样子,但如果您只是按照tqdm文档中给出的示例进行100次迭代,并且计算机很快,进度条没有时间更新,那么这可能不具有指导意义。也许使用像我下面提供的更大的数据集会更有帮助。

示例1:

from tqdm import tqdm # version 4.62.2
import pandas as pd # version 1.4.1
import numpy as np

tqdm.pandas(desc='My bar!') # lots of cool paramiters you can pass here. 
# the below line generates a very large dataset for us to work with. 
df = pd.DataFrame(np.random.randn(100000000, 4), columns=['a','b','c','d'])
# the below line will square the contents of each element in an column-wise 
# fashion 
df.progress_apply(lambda x: x**2)

输出:

输出

例子2:

# you could apply a function within the lambda expression for more complex 
# operations. And keeping with the above example... 

tqdm.pandas(desc='My bar!') # lots of cool paramiters you can pass here. 
# the below line generates a very large dataset for us to work with. 
df = pd.DataFrame(np.random.randn(100000000, 4), columns=['a','b','c','d'])

def function(x):
    return x**2
     
df.progress_apply(lambda x: function(x))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接