python

Saving dataframe in Excel with Pandas

I recently helped my friend process their financial data with Python. We came across this issue with Windows 10 running Python 3.7 throwing errors when I was trying to save a pandas data frame to an Microsoft Excel format .xlsx file.

So here is the Python code which runs perfectly on a Mac running Python 3.6.6,

import pandas as pd
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
df.to_excel('df.xlsx')

However, this code did not work on Windows for some reason. I got some error. Unfortunately I was not able to record the error as he took his laptop back.

After a few search on Google, I found this solution which worked perfect in Windows. So we can use XlsxWriter as the engine and use ExcelWriter to do this.

import pandas as pd
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('df.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Close the Pandas Excel writer and output the Excel file.
writer.save()

Original solution from stackoverflow here

 

 

 

Leave a comment