1

I have two different panda.DataFrame (df1 and df2). I want to write each dataframe into a separate sheet in the CSV file. In this link, all dataframes are written in the same sheet.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
S.EB
  • 1,966
  • 4
  • 29
  • 54
  • 1
    The CSV format does not support "separate sheets"; please see for example https://stackoverflow.com/questions/29615196/is-csv-with-multi-tabs-sheet-possible – Karl Knechtel May 29 '20 at 02:42
  • 2
    CSV is just a text file, it doesn't know about `sheet`. If you mean `excel`, you can see [this question](https://stackoverflow.com/questions/56034923/saving-multiple-dataframes-to-multiple-excel-sheets-multiple-times). – Quang Hoang May 29 '20 at 03:49

1 Answers1

3

CSV files don't support sheets.
You can use pd.to_excel and ExcelWriter to write in the same excel file:

first, install the openpyxl module if you don't have

python -m pip install openpyxl
with pd.ExcelWriter('output.xlsx') as writer:
    df1.to_excel(writer, sheet_name='df1')
    df2.to_excel(writer, sheet_name='df2')

Documentation here:
Pandas Docs

  • Is there also an option to write `writer = pd.ExcelWriter('output.xlsx')` ? I'm trying that right now and it's not working for me – tamtam Dec 07 '21 at 20:36
  • Hi tamtam. You installed/imported openpyxl lib? It works for me here. Share your code if you can. – Joao Figueiredo Dec 08 '21 at 23:48