如何在jupyter笔记本中使用tqdm和pandas?

时间:2016-11-07 23:47:27

标签: python pandas jupyter-notebook tqdm

我正在使用jupyter笔记本中的pandas进行一些分析,因为我的apply函数需要很长时间才能看到进度条。 通过这篇文章here,我找到了为pandas operations提供简单进度条的tqdm库。 还有一个Jupyter integration提供了一个非常好的进度条,其中条形本身随着时间的推移而变化。

但是,我想将两者结合起来,并不太明白如何做到这一点。 让我们采用文档中的相同示例

import pandas as pd
import numpy as np
from tqdm import tqdm

df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))

# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
# (can use `tqdm_gui`, `tqdm_notebook`, optional kwargs, etc.)
tqdm.pandas(desc="my bar!")

# Now you can use `progress_apply` instead of `apply`
# and `progress_map` instead of `map`
df.progress_apply(lambda x: x**2)
# can also groupby:
# df.groupby(0).progress_apply(lambda x: x**2)

它甚至说“可以使用'tqdm_notebook'”,但我找不到方法。 我尝试了一些像

这样的东西
tqdm_notebook(tqdm.pandas(desc="my bar!"))

tqdm_notebook.pandas

但它们不起作用。 在definition它看起来像

tqdm.pandas(tqdm_notebook(desc="my bar!"))

应该有效,但条形图没有正确显示进度,还有其他输出。

还有其他想法吗?

4 个答案:

答案 0 :(得分:11)

您可以使用:

tqdm_notebook().pandas(*args, **kwargs)

这是因为tqdm_notebook有一个延迟适配器,因此在访问其方法(包括类方法)之前必须进行实例化。

将来(> v5.1),您应该能够使用更统一的API:

tqdm_pandas(tqdm_notebook, *args, **kwargs)

答案 1 :(得分:2)

我发现我也必须导入-I。下面给出了一个适用于Jupyter笔记本的简单示例。

鉴于您要在变量上映射函数以在熊猫数据框中创建一个新变量。

tqdm_notebook

答案 2 :(得分:2)

我的工作解决方案(从documnetation复制):

from tqdm.auto import tqdm
tqdm.pandas()

答案 3 :(得分:0)

如果要为该缓慢的应用步骤使用多个CPU,请考虑使用swifter。另外,swiftertqdm步骤上自动启用apply进度栏。要自定义栏说明,请使用df.swifter.progress_bar(enable=True, desc='bar description').apply(...)