简体   繁体   English

将多个pandas数据帧转换为xlsx后如何压缩(单个zip文件)?

[英]how to zip (single zip file) multiple pandas dataframes after converting it to xlsx?

currently I am converting the dataframes to csv and then zipping using the following code:目前我正在将数据帧转换为 csv,然后使用以下代码进行压缩:

dfDict = {'df_1_name.csv': df1, 'df_2_name.csv': df2}

def makeZip(self, path, dfDict):
  fileNames = dfDict.keys()
  if len(fileNames) > 0:
    with zipfile.ZipFile(path, 'w') as csv_zip:
      for file in fileNames:
        csv_zip.writestr(file, dfDict[file].to_csv(index=False),zipfile.ZIP_DEFLATED)
  return

I found that pandas.DataFrame.to_excel function exists, but can't figure out how to use it in a similar way as above我发现pandas.DataFrame.to_excel函数存在,但无法弄清楚如何以与上述类似的方式使用它

You can use different sheets for your DataFrames, you can use something similar to:您可以为 DataFrame 使用不同的工作表,您可以使用类似于以下内容的内容:

with pd.ExcelWriter('output.xlsx') as writer:  
    df1.to_excel(writer, sheet_name='Sheet_name_1')
    df2.to_excel(writer, sheet_name='Sheet_name_2')

then, if you also want to zip it, just zip output.xlsx .然后,如果您还想压缩它,只需压缩output.xlsx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM