【问题标题】:Decimal Module output displaying incorrectly in Streamlit十进制模块输出在 Streamlit 中显示不正确
【发布时间】:2023-02-02 01:13:38
【问题描述】:

我有一个数据框,其中一列处理以欧元显示的货币。由于舍入问题,我想使用 DECIMAL 模块来获得精确的算术结果。

  • Python 命令:0.1 + 0.2 == 0.3 为 FALSE
  • Decimal 模块:Decimal('0.1')+Decimal('0.2') == Decimal('0.3') is TRUE(这是我正在寻找的场景)

木星笔记本

d = {'name': ["A", "B", "C"], 'amount': [0.1, 0.2, 0.3]}
df = pd.DataFrame(data=d)
print("Original")
print(df)
print("Original_Test")
print(df['amount'][0]+df['amount'][1]==df['amount'][2])

for col in df:
    if "amount" in col or "eur" in col:
        df[col] = list(df[col])
        df[col] = [Decimal(str(round(i,2))) for i in df[col]]
print("Decimal Layout")
print(df)
print("Decimal Layout_Test")
print(df['amount'][0]+df['amount'][1]==df['amount'][2])

当上面的代码运行到 Jupyter Notebook 中时,输出是正确的:

Jupyter Notebook

流光

d = {'name': ["A", "B", "C"], 'amount': [0.1, 0.2, 0.3]}
df = pd.DataFrame(data=d)
st.write(df)
for col in df:
    if "amount" in col or "eur" in col:
        df[col] = list(df[col])
        df[col] = [Decimal(str(round(i,2))) for i in df[col]]
st.write(df)
st.write(df['amount'][0]+df['amount'][1]==df['amount'][2])

然后将相同的代码适配到 Streamlit 并运行。即使输出被列为 TRUE,数量列也错误地显示为 [1, 2, 3] 而不是 [0.1, 0.2, 0.3]

Streamlit Output

【问题讨论】:

  • 不要将数据框显示为图像。您的问题需要一个最小的可重现示例,包括示例输入、预期输出、实际输出,以及仅重现问题所需的相关代码。有关 Pandas 问题的最佳实践,请参阅How to make good reproducible pandas examples

标签: python jupyter-notebook streamlit


【解决方案1】:

这与 streamlit 有关,以下是您可以使用 df.style.format() 方法在写入数据帧时重置小数点:

st.write(df.style.format({'amount': '{:.1f}'}))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2017-06-08
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2021-07-19
    相关资源
    最近更新 更多