You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决pandas中read_excel读取后to_csv写入浮点值不符问题

解决Excel转CSV时浮点数精度显示不一致的问题

问题根源在于:Excel界面显示的0.018311943169191是截断后的格式化结果,单元格实际存储的是更高精度的浮点数(也就是你看到的0.018311943169191037)。pandas默认读取的是单元格实际存储的数值,而非界面显示的文本,所以转CSV后会输出完整精度值。

下面是几种可行的修复方案:

方案1:直接读取Excel的显示文本(最精准)

用openpyxl读取每个单元格的显示值,完全复刻Excel界面的内容,需要先安装openpyxl:

pip install openpyxl

然后执行代码:

import pandas as pd
from openpyxl import load_workbook

# 加载Excel文件,data_only=True确保读取计算后的值
wb = load_workbook("你的xlsx文件路径.xlsx", data_only=True)
ws = wb.active

# 获取表头行
headers = [cell.value for cell in ws[1]]
# 遍历所有数据行,读取每个单元格的显示文本
data_rows = []
for row in ws.iter_rows(min_row=2, values_only=False):
    data_rows.append([cell.display_value for cell in row])

# 转成DataFrame后写入CSV
df = pd.DataFrame(data_rows, columns=headers)
df.to_csv("输出csv文件路径.csv", encoding="utf-8", index=False)

方案2:按指定小数位数格式化数值

如果你确定目标列的小数位数是15位(和Excel显示一致),可以读取数值后格式化字符串:

import pandas as pd

df = pd.read_excel("你的xlsx文件路径.xlsx")
# 格式化为15位小数,确保和Excel显示一致
df["my column"] = df["my column"].apply(lambda x: f"{x:.15f}")
# 如果需要去掉末尾多余的0,改用下面这行:
# df["my column"] = df["my column"].apply(lambda x: f"{x:.15f}".rstrip("0").rstrip(".") if "." in f"{x:.15f}" else f"{x:.15f}")

df.to_csv("输出csv文件路径.csv", encoding="utf-8", index=False)

方案3:用openpyxl引擎读取为字符串

之前尝试的converters参数没生效,可能是默认引擎的问题,改用openpyxl引擎读取字符串:

import pandas as pd

# 指定openpyxl引擎,直接将目标列读取为字符串
df = pd.read_excel("你的xlsx文件路径.xlsx", converters={"my column": str}, engine="openpyxl")
df.to_csv("输出csv文件路径.csv", encoding="utf-8", index=False)

内容的提问来源于stack exchange,提问作者archjkeee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:17:39