Pandas 到 Excel,小数列正在转换为文本

问题描述 投票:0回答:1
df['some_col1'] = df['some_col1'].apply(lambda x: Decimal(x) if pd.notnull(x) else None)
df['some_col2'] = df['some_col2'].apply(lambda x: Decimal(x) if pd.notnull(x) else None)
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
        df.to_excel(writer, index=False, sheet_name='Sheet1')
        workbook = writer.book
        worksheet = writer.sheets['Sheet1']
        
        # Define number format
        number_format = workbook.add_format({'num_format': '0.0000'})
        
        # Apply formatting based on column name
        for col_num, col_name in enumerate(df.columns):
            if col_name == 'some_col1' or col_name == 'some_col2':  # Specify by column name
                  worksheet.set_column(col_num, col_num, None, number_format)

即使我直接在 set_column 中指定列(例如“A:A”)也不起作用

列肯定是小数,但在 Excel 工作表中它们是文本格式:

enter image description here

谢谢

python excel pandas
1个回答
0
投票

已知问题,Github问题链接:link

Pandas to_excel 方法中,decimal.Decimal 值被保存为文本是由于 Pandas 无法将其识别为数字类型。

要解决此问题,您可以将小数点修改为浮动:

df['some_col1'] = df['some_col1'].apply(lambda x: float(Decimal(x)) if pd.notnull(x) else None)
df['some_col2'] = df['some_col2'].apply(lambda x: float(Decimal(x)) if pd.notnull(x) else None)

这将被识别为数字类型,而不是 Excel 中的文本。

© www.soinside.com 2019 - 2024. All rights reserved.