简体   繁体   中英

How do I suppress scientific notation in pandas DF when exporting to an excel file?

I need to export a Data Frame to an excel file with big natural numbers without decimals like 1234567890123456789 by example, and the output in the excel file should be a number (not a string).

I have found a lot of solutions to suppress scientific notation, but those solutions are using a string instead of a number, or you need to use a number with decimals like 0.00001 by example (and I need to use just natural numbers, not decimals).

There is any way to do what I need?

Just in case, here is how I manage the data:

# Reading:
excel_file = pd.ExcelFile(filename_in)
# I read some data frames like this:
df = pd.read_excel(excel_file, sheet)
# I perform operations with the data frames

# Exporting to excel (.xlsx):
excel_writer = pd.ExcelWriter(filename_out, engine='xlsxwriter')

# I do this with all the data frames:
df.to_excel(excel_writer, sheet_name=sheet, index=False)

# After all the changes:
excel_writer.save()

Integers like 1234567890123456789 are too big to be handled by Excel.

Numbers in Excel are stored as IEEE 754 Doubles which have a (general) precision of 15 digits. So, if you pasted 1234567890123456789 into Excel it would be stored in the file format as 1.2345678901234501E+18 and displayed, depending on the format, as 1234567890123450000.

So, in short, you aren't going to be able to store numbers like that in Excel without losing precision or without storing them as strings (hence the recommendations you saw elsewhere).

For the more general question here is an example of setting the number format for a dataframe output to Excel:

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Numbers':    [0.001112, 0.002224, 0.003335, 0.004547]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_column_formats.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a number format.
format1 = workbook.add_format({'num_format': '0.00000'})

# Set the column width and format.
worksheet.set_column(1, 1, 18, format1)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM