CodeWalk

tqdm基础用法与多层级进度条

作者:编译有声 · 2026-05-30 12:55

tqdm是Python最流行的进度条库。请介绍tqdm的基本用法(tqdm(range(n))、手动更新、自定义描述)、多层级进度条(tqdm.tqdm嵌套/external模式)以及配合pandas progress_apply的使用方法。

回答

编译有声

基础用法

from tqdm import tqdm
import time

# 最简单用法
for i in tqdm(range(100)):
    time.sleep(0.01)

# 自定义描述
tqdm(range(100), desc='处理中', unit='item', leave=True)

# 可迭代对象
with tqdm(total=100, desc='下载进度') as pbar:
    for chunk in data_stream:
        process(chunk)
        pbar.update(len(chunk))  # 手动更新

# 设置后缀信息
pbar.set_postfix(loss=0.85, acc=0.92)

嵌套进度条

方法1:tqdm.notebook.trange嵌套(Jupyter友好)

方法2:外部模式(position参数)

from tqdm import tqdm
import time

# 外层epoch
outer = tqdm(range(5), desc='Epoch', position=0)
for epoch in outer:
    # 内层batch
    inner = tqdm(range(50), desc=f'Batch', position=1, leave=False)
    for batch in inner:
        time.sleep(0.01)
        inner.set_postfix(loss=0.1)
    outer.update(1)

pandas集成

import pandas as pd
df = pd.DataFrame({'a': range(1000)})

# 方式1: tqdm.pandas
tqdm.pandas(desc='处理行')
df['result'] = df['a'].progress_apply(lambda x: x ** 2)

# 方式2: progress_map (tqdm内置)
from tqdm.auto import tqdm
df.progress_map(lambda x: x ** 2)

高级功能

  • tqdm.auto:自动选择最佳渲染(终端/Jupyter)
  • tqdm.contrib.concurrent.thread_map/process_map:多线程/进程并行进度
  • tqdm.write():输出文字不打断进度条
  • 支持refresh()close()方法

注意:嵌套进度条在Jupyter中兼容性更好,终端需设置position参数。