【问题标题】:How do I suppress scientific notation in pandas DF when exporting to an excel file?导出到 excel 文件时如何抑制 pandas DF 中的科学记数法?
【发布时间】:2020-11-12 00:35:51
【问题描述】:

我需要将一个数据框导出到一个带有大自然数的 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()

【问题讨论】:

    标签: python excel pandas xlsxwriter python-3.8


    【解决方案1】:

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

    Excel 中的数字存储为IEEE 754 Doubles,其(一般)精度为 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()
    

    输出:

    【讨论】:

    • 我需要管理的数字是自然数,我不需要管理十进制数,但是您已经回答了我的问题,谢谢! :)
    猜你喜欢
    • 2021-06-17
    • 2014-05-24
    • 2020-05-31
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多