【问题标题】:How to see the progress bar of read_csv如何查看read_csv的进度条
【发布时间】:2019-07-24 01:17:56
【问题描述】:

我正在尝试读取 100GB 大小的 csv 文件
我想在他们阅读文件时看到 profess bar

file = pd.read_csv("../code/csv/file.csv") 

喜欢 =====> 30%
阅读 read_csv 时有没有办法看到进度条?或其他文件

【问题讨论】:

  • 取决于您阅读文件的方式。如果您有要迭代的内容,tqdmprogressbar2 可以处理,但是对于单个原子操作,通常很难获得进度条(因为您实际上无法进入操作以查看多远你在任何给定的时间)。我认为 tqdm 中的 HTTP 请求有一些解决方法,但我认为 pandas 不存在。
  • 我只推荐使用块

标签: python pandas csv


【解决方案1】:
import os
import sys
from tqdm import tqdm

temp = pd.read_csv(INPUT_FILENAME, nrows=20)
N = len(temp.to_csv(index=False))
df = [temp[:0]]
t = int(os.path.getsize(fn)/N*20/10**5) + 1
with tqdm(total = t, file = sys.stdout) as pbar:
    for i,chunk in enumerate(pd.read_csv(fn, chunksize=10**5, low_memory=False)):
        df.append(chunk)
        pbar.set_description('Importing: %d' % (1 + i))
        pbar.update(1)

data = temp[:0].append(df)
del df            

【讨论】:

  • 一些代码 cmets 或对这些变量中的任何一个的解释将有助于这个答案。
【解决方案2】:

带有 typer 模块的精美输出,我在 Jupyter Notebook 中测试过,其中包含一个包含 618k 行的大型分隔文本文件。


from pathlib import Path
import pandas as pd
import tqdm
import typer

txt = Path("<path-to-massive-delimited-txt-file>").resolve()

# read number of rows quickly
length = sum(1 for row in open(txt, 'r'))

# define a chunksize
chunksize = 5000

# initiate a blank dataframe
df = pd.DataFrame()

# fancy logging with typer
typer.secho(f"Reading file: {txt}", fg="red", bold=True)
typer.secho(f"total rows: {length}", fg="green", bold=True)

# tqdm context
with tqdm.auto.tqdm(total=length, desc="chunks read: ") as bar:
    # enumerate chunks read without low_memory (it is massive for pandas to precisely assign dtypes)
    for i, chunk in enumerate(pd.read_csv(txt, chunksize=chunksize, low_memory=False)):
        
        # print the chunk number
        print(i)
        
        # append it to df
        df = df.append(other=chunk)
        
        # update tqdm progress bar
        bar.update(chunksize)
        
        # 6 chunks are enough to test
        if i==5:
            break
            
# finally inform with a friendly message
typer.secho("end of reading chunks...", fg=typer.colors.BRIGHT_RED)
typer.secho(f"Dataframe length:{len(df)}", fg="green", bold=True)
    

Jupyter Notebook Output - png

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多