4
\$\begingroup\$

I have a lot of compressed csv files in a directory. I want to read all those files in a single dataframe. This is what I have done till now:

df = pd.DataFrame(columns=col_names)
for filename in os.listdir(path):
 with gzip.open(path+"/"+filename, 'rb') as f:
 temp = pd.read_csv(f, names=col_names)
 df = df.append(temp)

I have noticed that the above code runs quite fast initially, but it keeps on getting slower and slower as it reads more and more files. How can I improve this?

AlexV
7,3532 gold badges24 silver badges47 bronze badges
asked Jan 15, 2020 at 13:29
\$\endgroup\$
2
  • \$\begingroup\$ what's your files extension .tar.gz or .gz ? \$\endgroup\$ Commented Jan 15, 2020 at 13:36
  • \$\begingroup\$ @RomanPerekhrest file extension is .gz \$\endgroup\$ Commented Jan 15, 2020 at 13:40

1 Answer 1

5
\$\begingroup\$

Ultimate optimization

  • avoid calling pd.DataFrame.append function within a loop as it'll create a copy of accumulated dataframe on each loop iteration. Apply pandas.concat to concatenate pandas objects at once.

  • no need to gzip.open as pandas.read_csv already allows on-the-fly decompression of on-disk data.

    compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’

  • avoid hardcoding filepathes with path+"/"+filename. Instead use suitable os.path.join feature: os.path.join(dirpath, fname)


The final optimized approach:

import os
import pandas as pd
dirpath = 'path_to_gz_files' # your directory path
df = pd.concat([pd.read_csv(os.path.join(dirpath, fname))
 for fname in os.listdir(dirpath)], ignore_index=True)
answered Jan 15, 2020 at 14:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.