Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: to_excel() float_format

I'm trying to get the float_format parameter working with pandas' to_excel() function, but it doesn't seem to do anything.

Code:

df = pd.DataFrame({
        'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
        'numA':[1000,2000,3000,4000.3],
        'numB':[10000,20000.2,30000,40000]
    })

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')

print df.dtypes

df.to_excel(writer, 
        index = False,
        float_format = '%.2f',
    )

But the Excel file looks like this:

enter image description here

I confirmed dtypes as:

date     object
numA    float64
numB    float64
dtype: object

Does anyone know how to properly format floats in to_excel()?

like image 908
elPastor Avatar asked Jun 07 '17 21:06

elPastor


People also ask

How do I convert a DataFrame to Xlsx in Python?

Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.

Can pandas format excel?

Pandas makes it very easy to output a DataFrame to Excel. However, there are limited options for customizing the output and using Excel's features to make your output as useful as it could be.

How do I view excel files in pandas?

We can use the pandas module read_excel() function to read the excel file data into a DataFrame object. If you look at an excel sheet, it's a two-dimensional table. The DataFrame object also represents a two-dimensional tabular data structure.

How do I export pandas to excel without index?

Pandas to_excel() function has number of useful arguments to customize the excel file. For example, we can save the dataframe as excel file without index using “index=False” as additional argument. One of the common uses in excel file is naming the excel sheet.


1 Answers

I believe Excel formatting changes how floats are displayed. I tried to_csv method and float_format worked. For excel, telling excel how to display the column helps:

df = pd.DataFrame({
        'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
        'numA':[1000,2000,3000,4000.3],
        'numB':[10000,20000.2,30000,40000]
    })

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.00'})
worksheet.set_column('C:C', None, format1)  # Adds formatting to column C
writer.save()

Result:

Final excel result

More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

like image 90
Akshit Khurana Avatar answered Oct 21 '22 23:10

Akshit Khurana