Skip to content
Advertisement

Preserve formatting during excel file split with python

Hi I’m starting with python and have a question that sounds pretty simple, but at this point I don’t know how to solve it. I have a code for splitting some reports by columns. Unfortunately, I noticed that the format in output files changes during the split compared to the master file.

__ Dates format changes from short date: 9/29/2005 to 2005-09-29 00:00:00

__ Also number format changes from currencies to ‘standard’ number: 172,057.60 to: 172057.60

I’m struggling to find a solution to this. So far, I have found a lot of formatting information, but I have failed to apply them to the entire columns of the output files. Also it is important that dates don’t turn into strings. Would you help me rewrite the code to get exactly the same formatting as in the master file?

I think that the problem might be related with how .to_excel works, but I’m not sure.

JavaScript

Original file ; File after split

Advertisement

Answer

To set the date and/or datetime format in the pandas to_excel() output you will need to use an ExcelWriter object. Something like this:

JavaScript

To set the currency is a bit trickier. You will need to get access to the underlying Excel engine in Pandas and use that. Something like this:

JavaScript

See Working with Python Pandas and XlsxWriter.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement