I have 3 dataframes. Two of them I want to save in one worksheet, third I want to save in another worksheet. In the end, 2 worksheets should be in one xlsx file. How can I do that? Thanks for your help.
Asked
Active
Viewed 167 times
-1
-
4Does this answer your question? [creating multiple excel worksheets using data in a pandas dataframe](https://stackoverflow.com/questions/21981820/creating-multiple-excel-worksheets-using-data-in-a-pandas-dataframe) – Phoenixo Jul 16 '20 at 12:34
-
I don't know how to combine these 2 things: 2 dataframes in one worksheet and 2 worksheets in one xlsx file. I found solutions to these problems one at a time, but they were so different (different methods) that I have no way of combining them. – Michal Jul 16 '20 at 12:45
-
When you want 2 dataframes in one worksheet, do these 2 dataframes have same column names ? – Phoenixo Jul 16 '20 at 13:00
-
No, they have other names – Michal Jul 16 '20 at 13:05
-
Check my answer and tell me if it's what you needed – Phoenixo Jul 16 '20 at 13:13
1 Answers
0
Here is an example with 3 dataframes at beginning. Then I concatenate the dataframes df2
and df3
into df_concat
. Finally I save df1
in first worksheet, and df_concat
in second worksheet :
import xlsxwriter
import pandas as pd
df1 = pd.DataFrame({'col1': [1,2], 'col2': [3,4]})
df2 = pd.DataFrame({'A': [11,22], 'B': [33,44]})
df3 = pd.DataFrame({'C': [55,66], 'D': [77,88], 'E': [99,100]})
df_concat = pd.concat([df2, df3], axis=1)
writer = pd.ExcelWriter('my_multiple_worksheets_excel.xlsx', engine='xlsxwriter')
df1.to_excel(writer, sheet_name='Sheet_a')
df_concat.to_excel(writer, sheet_name='Sheet_b')
writer.save()

Phoenixo
- 2,071
- 1
- 6
- 13
-
Thanks, but it not solved my problem. 2 dataframes cant be concatenating, because they have a different number and column names – Michal Jul 16 '20 at 13:42
-
I edited my answer with `axis=1` in the concatenation and some modifications in dataframes. Check if this is good now :) – Phoenixo Jul 16 '20 at 14:00
-
No :( There are 2 independet tables. I just want to put it in worksheet with 2 of headers with column names. – Michal Jul 16 '20 at 14:06