Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

write 2 dataframes in 2 different excel sheets

I was trying something like this:

output_2df = pd.concat([installs, second_installs], ignore_index=True)
output_2df.to_excel('./installs.xlsx',sheet_name='Answers')

output_qdf = pd.concat([a_questionnaires, b_questionnaires], ignore_index=True)
output_qdf.to_excel('./installs.xlsx',sheet_name='questionnaires')

Although it works without an error, when I open my Excel file, I only see the second sheet. The data from the first dataframe seems to be overwritten.

Then I tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

writer = pd.ExcelWriter('./installs.xlsx', engine='openpyxl')

# Append final dfs to one output_df

output_2df = pd.concat([installs, second_installs], ignore_index=True)
output_2df.to_excel(writer, sheet_name='Answers')


output_qdf = pd.concat([a_questionnaires, b_questionnaires], ignore_index=True)
output_qdf.to_excel(writer, sheet_name='Questionnaires')

However, in this case when I open my Excel file manually, I get an error that it cannot be opened since the file type is invalid.

What’s the correct way to write two different dataframes to 2 separate sheets in the same Excel file?

>Solution :

You can use pd.ExcelWriter for this:

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('file_name.xlsx', engine='xlsxwriter')
# Write each dataframe to a different worksheet.
clean_year_examens.to_excel(writer, sheet_name='Examens jaar')
df1.to_excel(writer, sheet_name='sheet_name1')
df2.to_excel(writer, sheet_name='sheet_name2')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading