pandas to_excel()方法在Excel中查看时会强制对int64列进行科学计数

时间:2018-11-06 01:06:20

标签: python openpyxl

我正在使用以下代码将数据框保存到excel:

    writer = pd.ExcelWriter(self.file_name, engine='openpyxl')
    writer.book = workbook
    writer.sheets = dict((ws.title, ws) for ws in workbook.worksheets)
    df.to_excel(writer, sheet_name=sheet_name, columns=columns, header=True, index=False, startrow=11, startcol=0)
    writer.save()

不幸的是,任何具有大int64 dtype的列都会如下所示:

enter image description here

在熊猫内,我通过执行以下操作来压制科学计数法:

pd.set_option('display.float_format', lambda x: '%.f' % x) 
pd.set_option('display.precision', 0)

因此,当我打印数据框时,int64列如下所示:

enter image description here

我尝试将列转换为str类型,如下所示:

    def convert_int_cols_to_str(df):
        dtypes = df.dtypes
        for col, dtype in dtypes.iteritems():
            if dtype == 'int64':
                df[col] = df[col].astype(str)

在此之后,这些列的dtypes显示为对象而不是int64,但仍在Excel中以科学计数法显示。 关于如何避免这种情况的任何想法将不胜感激!

以下是我使用的相关软件包的版本:

openpyxl==2.5.9
pandas==0.20.3

1 个答案:

答案 0 :(得分:0)

哇,对不起大家。原来我在脚本的错误位置应用了dtype转换。我上面描述的方法实际上可以完美地抑制Excel中int64列的科学计数法。我将不去回答这个问题,以防它可以帮助其他人。