【问题标题】:How to prevent the format change of a dataframe when copied into a Excel file?复制到 Excel 文件时如何防止数据框的格式更改?
【发布时间】:2022-12-24 00:58:33
【问题描述】:

我有以下 python 代码行,它将数据框的内容复制到 Excel 文件中:

unified_dataframe.to_excel('FinancialAnalysis_'+timestr+'_.xlsx', sheet_name='Banks', index=False)

我的数据框的前两列包含格式为文本的数据,但数据框的其余列的数据格式为浮点数,但是当将它们插入 Excel 文件时,它们将作为文本插入。我怎样才能防止这种情况或将感兴趣的 Excel 列从文本转换为浮动(不包括标题)?

【问题讨论】:

  • “格式化为浮点数”是什么意思?请分享一些示例数据(例如unified_dataframe.head(),以及unified_dataframe.dtypes的结果。

标签: python excel pandas


【解决方案1】:

我猜你可以使用 apply 库的 apply 方法将 DataFrame 中特定列的值转换为不同的数据类型

import pandas as pd

df = pd.read_excel('FinancialAnalysis.xlsx')
df['Column Name'] = df['Column Name'].apply(float)
df.to_excel('FinancialAnalysis_modified.xlsx', index=False)

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2017-10-08
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 2021-04-09
    • 2022-01-24
    相关资源
    最近更新 更多