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

Streamlit中如何保留数据两位小数?CSV导入后小数位数异常

解决Pandas/Streamlit中表格显示及导出CSV保留两位小数的问题

核心思路

问题源于Pandas处理数据时自动扩展了小数位数,我们可以通过设置表格显示格式和导出CSV时指定小数格式两个方向解决:


1. 修改表格显示格式(Streamlit展示时保留两位小数)

在使用.style.background_gradient()的同时,添加format()方法指定浮点列的显示规则:

针对category_df的修改:

with st.expander("Table"):
    # 先设置浮点列显示两位小数,再应用背景渐变样式
    styled_df = category_df.style.format("{:.2f}").background_gradient(cmap="Blues")
    st.write(styled_df)
    csv = category_df.to_csv(index=False).encode('utf-8')
    st.download_button("Download", data=csv, file_name="file.csv", mime="text/csv",
                       help='Click here to download')

针对sub_category_Year的修改:

with st.expander("Table"):
    df_selection["month"] = df_selection["date"].dt.month_name()
    sub_category_Year = pd.pivot_table(data=df_selection, values="amount", index=["name"], columns="month")
    # 对透视表的数值列强制显示两位小数
    styled_pivot = sub_category_Year.style.format("{:.2f}").background_gradient(cmap="Blues")
    st.write(styled_pivot)

针对df_selection的修改:

with st.expander("filtered"):
    # 对筛选后的表格设置浮点列显示格式
    styled_filtered = df_selection.iloc[:500, 0:20:1].style.format("{:.2f}").background_gradient(cmap="Blues_r")
    st.write(styled_filtered)

2. 修改导出CSV的格式(确保下载文件也是两位小数)

如果需要下载的CSV文件同样严格保留两位小数,修改to_csv()方法时添加float_format参数:

csv = category_df.to_csv(index=False, float_format="%.2f").encode('utf-8')

可选:全局设置Pandas浮点显示格式

如果希望所有DataFrame的浮点列默认显示两位小数,可在代码开头添加全局配置:

import pandas as pd
pd.options.display.float_format = "{:.2f}".format

注意:全局设置仅影响表格显示效果,导出CSV仍需单独设置float_format参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:43:24