如何让 tqdm 在 pandas 应用上工作?

Fan*_*ion 6 python pandas tqdm

Tqdm 文档显示了 tqdm 使用 Progress_apply 处理 pandas apply 的示例。我从这里https://tqdm.github.io/docs/tqdm/改编了以下代码,该代码通常需要几分钟才能执行(func1 是一个正则表达式函数)。

from tqdm import tqdm
tqdm.pandas()
df.progress_apply(lambda x: func1(x.textbody), axis=1)
Run Code Online (Sandbox Code Playgroud)

生成的进度条不显示任何进度。它只是从循环开始时的 0 跳到循环结束时的 100。我当前正在运行 tqdm 版本 4.61.2

小智 14

将 tqdm 与 pandas 结合使用

一般来说,人们在对列或行执行操作时倾向于使用 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)
Run Code Online (Sandbox Code Playgroud)

输出:

输出

示例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))
Run Code Online (Sandbox Code Playgroud)