簡體   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