user11173832
user11173832

Reputation:

How to see the progress bar of read_csv

I'm trying to read 100GB size of csv file
I want to see the profess bar when they reading file

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

like =====> 30%
is there way to see the progress bar when reading the read_csv? or other files

Upvotes: 14

Views: 10801

Answers (2)

Ofer Rahat
Ofer Rahat

Reputation: 878

The idea is to read a few lines from the large file to estimate line size, and then to iterate chunks of the file.

import os
import sys
from tqdm import tqdm


INPUT_FILENAME = f"{BASE_PATH}betas_R_SWAN_offset_100.csv.gz"
LINES_TO_READ_FOR_ESTIMATION = 20
CHUNK_SIZE_PER_ITERATION = 10**5


temp = pd.read_csv(INPUT_FILENAME,
                   nrows=LINES_TO_READ_FOR_ESTIMATION)
N = len(temp.to_csv(index=False))
df = [temp[:0]]
t = int(os.path.getsize(INPUT_FILENAME)/N*LINES_TO_READ_FOR_ESTIMATION/CHUNK_SIZE_PER_ITERATION) + 1


with tqdm(total = t, file = sys.stdout) as pbar:
    for i,chunk in enumerate(pd.read_csv(INPUT_FILENAME, chunksize=CHUNK_SIZE_PER_ITERATION, low_memory=False)):
        df.append(chunk)
        pbar.set_description('Importing: %d' % (1 + i))
        pbar.update(1)

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

Upvotes: 4

OzInClouds
OzInClouds

Reputation: 71

A fancy output with typer module, which I have tested in Jupyter Notebook with a massive delimited text file having 618k rows.


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

Upvotes: 3

Related Questions