繁体   English   中英

导出到 excel 文件时,如何抑制 Pandas DF 中的科学记数法?

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

我需要将一个数据框导出到一个带有大自然数的 excel 文件中,例如 1234567890123456789,并且excel文件中的输出应该是一个数字(而不是字符串)。

我找到了很多抑制科学记数法的解决方案,但是这些解决方案使用的是字符串而不是数字,或者您需要使用带有小数的数字,例如 0.00001(我只需要使用自然数,而不是小数) .

有什么办法可以做我需要的吗?

以防万一,这是我管理数据的方式:

# 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()

像 1234567890123456789 这样的整数太大,Excel 无法处理。

Excel 中的数字存储为IEEE 754 双精度数,其(一般)精度为 15 位。 因此,如果您将 1234567890123456789 粘贴到 Excel 中,它将以文件格式存储为 1.2345678901234501E+18 并根据格式显示为 1234567890123450000。

因此,简而言之,您将无法在不丢失精度或不将它们存储为字符串的情况下在 Excel 中存储这样的数字(因此是您在其他地方看到的建议)。

对于更一般的问题,这里是将数据帧输出的数字格式设置为 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()

输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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