+2 votes
in Programming Languages by (14.6k points)
edited by
I want to create a zipped CSV file that will contain a dataframe. How can I do this?

1 Answer

0 votes
by (25.6k points)

You need to use to_csv() function with parameter 'compression'. The valid compression types are ['infer', None, 'bz2', 'gzip', 'xz', 'zip'].

Here is an example to save a dataframe in a zipped file.

import pandas as pd
dd = {'A':[1,2,3,4,5],'B':[10,20,30,40,50],'C':[100,200,300,400,500]}
df = pd.DataFrame(dd)
print(df)

# save dataframe as a zipped file
df.to_csv('out.zip', index=False, compression='zip')

# read from the saved zipped file
df1 = pd.read_csv('out.zip', compression='zip')
print(df1)

...