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

Pandas DataFrame转字典时保留两位小数(如0.0显示为0.00)

问题根因

Python原生float类型中,0.0和0.00是完全等价的同一个值,解释器不会保留末尾的占位0。pandas在打印DataFrame时显示的0.00只是展示层的格式化效果,并没有修改浮点数本身的值,所以调用to_dict()导出时会直接返回原生浮点值。你之前直接遍历把0.0替换为0.00不生效,也是因为赋值的浮点型0.00本质还是0.0。

可行方案

根据你后续使用字典的场景二选一即可:

  • 方案1:保留数值计算能力,用Decimal类型固定小数位
    如果导出的字典后续还需要做数值运算,用标准库Decimal类型存储值,可以固定保留两位小数的格式,不会自动省略末尾的0。修改后的代码如下:
import pandas as pd
from tkinter import *
from decimal import Decimal


def create():
    data = {'1': [0.99999, 0.00000, 1.22222, 0.000000], '2': [0.99999, 0.00000, 1.22222, 0.000000]}
    df = pd.DataFrame(data)
    df2 = df.round(decimals = 2)
    my_dictionary = df2.to_dict()
    # 遍历字典统一量化为两位小数
    for col_key in my_dictionary:
        for row_key in my_dictionary[col_key]:
            raw_val = my_dictionary[col_key][row_key]
            my_dictionary[col_key][row_key] = Decimal(str(raw_val)).quantize(Decimal('0.00'))
    print(my_dictionary)


window = Tk()
window.geometry("200x200")
button = Button(text="Convert",command=create)
button.pack()
window.mainloop()

运行后输出结果:
{'1': {0: Decimal('1.00'), 1: Decimal('0.00'), 2: Decimal('1.22'), 3: Decimal('0.00')}, '2': {0: Decimal('1.00'), 1: Decimal('0.00'), 2: Decimal('1.22'), 3: Decimal('0.00')}}

  • 方案2:仅用于展示,直接格式化为字符串
    如果字典只用于前端展示、文本导出,不需要做数值计算,直接把值格式化为两位小数的字符串即可,修改遍历部分代码:
for col_key in my_dictionary:
    for row_key in my_dictionary[col_key]:
        my_dictionary[col_key][row_key] = f"{my_dictionary[col_key][row_key]:.2f}"

输出结果中所有值都是固定两位小数的字符串:
{'1': {0: '1.00', 1: '0.00', 2: '1.22', 3: '0.00'}, '2': {0: '1.00', 1: '0.00', 2: '1.22', 3: '0.00'}}

注:你示例中写的期望输出保留1.0的格式是无法和0.00同时实现的——只要是数值类型,要么统一保留两位小数显示为1.00/0.00,要么自动省略末尾0显示为1.0/0.0,浮点类型本身不支持区分这两种展示形态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:15:35