【问题标题】:Pandas to_csv progress bar with tqdm带有 tqdm 的 Pandas to_csv 进度条
【发布时间】:2020-11-05 10:30:47
【问题描述】:

正如标题所示,我正在尝试在执行pandas.to_csv 时显示进度条。
我有以下脚本:

def filter_pileup(pileup, output, lists):
    tqdm.pandas(desc='Reading, filtering, exporting', bar_format=BAR_DEFAULT_VIEW)
    # Reading files
    pileup_df = pd.read_csv(pileup, '\t', header=None).progress_apply(lambda x: x)
    lists_df = pd.read_csv(lists, '\t', header=None).progress_apply(lambda x: x)
    # Filtering pileup
    intersection = pd.merge(pileup_df, lists_df, on=[0, 1]).progress_apply(lambda x: x)
    intersection.columns = [i for i in range(len(intersection.columns))]
    intersection = intersection.loc[:, 0:5]
    # Exporting filtered pileup
    intersection.to_csv(output, header=None, index=None, sep='\t')

在前几行我找到了一种集成进度条的方法,但这种方法不适用于最后一行,我该如何实现?

【问题讨论】:

  • 以一种非常 hacky 的方式,您可以创建一个从 io.TextIOBase 周围的 output 继承的包装类,该类将 .write 调用传递给 output,同时更新进度条。不过不推荐,所以我不会将其发布为答案。
  • 您找到解决方案了吗?如果您能将其发布为答案,我将不胜感激:)
  • @Sierox 我还没有找到解决这个确切问题的方法,但最终,我使用了 dask 模块,而不是 pandas,该模块本身在dask.diagnostics下有一个进度条@

标签: python pandas tqdm


【解决方案1】:

您可以将数据帧划分为 n 行的块,然后将数据帧逐块保存到 csv 块中,第一行使用 mode='w',其余行使用 mode="a":

例子:

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

df = pd.DataFrame(data=[i for i in range(0, 10000000)], columns = ["integer"])

print(df.head(10))

chunks = np.array_split(df.index, 100) # chunks of 100 rows

for chunck, subset in enumerate(tqdm(chunks)):
    if chunck == 0: # first row
        df.loc[subset].to_csv('data.csv', mode='w', index=True)
    else:
        df.loc[subset].to_csv('data.csv', header=None, mode='a', index=True)

输出:

   integer
0        0
1        1
2        2
3        3
4        4
5        5
6        6
7        7
8        8
9        9

100%|██████████| 100/100 [00:12<00:00,  8.12it/s]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 2021-03-08
相关资源
最近更新 更多