I have a few DataFrames that I need to zip to one file. This is my code:
df_list = [ojcowskieDF,mateczneDF]
with zipfile.ZipFile('final.zip', 'w') as zipF:
for file in df_list:
zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)
But I get this error:TypeError: stat: path should be string, bytes, os.PathLike or integer, not DataFrame
Does anyone know how to zip a few DF? Thanks for your help
CodePudding user response:
You need first to convert your dataframes to .csv by using pandas.DataFrame.to_csv
or to .xlsx by using pandas.DataFrame.to_excel
.
import zipfile
import os
list_df = [ojcowskieDF, mateczneDF]
with zipfile.ZipFile('final.zip', 'w') as zf:
i=1 #this iterator to make sure each .csv will have a different name
for df in list_df:
df.to_csv(f'sample_{i}.csv') #this will convert the dataframe to a .csv
zf.write(f'sample_{i}.csv') #this will put the .csv in the zipfile
os.remove(f'sample_{i}.csv') #this will delete the .csv created
i =1