+2 votes
in Programming Languages by (15.7k 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 (27.1k 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)

# 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')