pandas - 使用 Python 中的 StyleFrame 库在 Excel 中显示尾随零时出现问题

标签 pandas formatting precision export-to-excel styleframe

在使用 StyleFrame 库写入 excel 文件时,如果有尾随零,我无法保留 3 个小数位。

例如,考虑以下数据框:

dataframe df with two columns, "Security Name" and "MGEAFE %Port"

接下来,我将此数据框写入 StyleFrame 对象以进行数据格式化,最后,将 StyleFrame 对象写入 excel 文件:

sf = StyleFrame(df)
sf = sf.apply_headers_style(...)
sf = sf.apply_column_style(...)
sf.to_excel(writer, float_format="%.3f")

这是我的输出:

output

我想做的是,将 0.08 显示为 0.080,因为我的浮点格式在 to_excel() 调用中建议使用“%.3f”。

有什么建议吗?

最佳答案

嗯,因为 df.to_excel(writer, float_format='%.3f') 没有提供预期的输出,sf.to_excel(writer, float_format="%.3f") 也不会(StyleFrame.to_excel 将它无法识别的 kwargs 传递给 pandas.DataFrame.to_excel)。

您可以通过在设置列样式时使用自定义 number_format 来使其正常工作。将 number_format='0.000'('0.000' 是 Excel 用来表示小数点后 3 位的单元格格式)传递给您要创建的 Styler 对象用于设置 MGEAFE %port 列的样式。

from StyleFrame import StyleFrame, Styler


df = pd.DataFrame({'a': [0.021, 0.029, 0.080]})
StyleFrame(df, Styler(number_format='0.000')).to_excel('test.xlsx').save()

enter image description here

关于pandas - 使用 Python 中的 StyleFrame 库在 Excel 中显示尾随零时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51308619/

相关文章:

python - 在不使用 for 循环的情况下重新格式化数据框

python - 类型错误 : float() argument must be a string or a number, 而不是 'NaTType'

css - 为什么子div的边距会影响父div的边距?

java - 我如何在java中使用printf来打印格式化输出

html - 如何向 Gmail 添加格式良好的 HTML 签名?附言复制和粘贴不起作用

c++ - 当存在 float 精度问题时,如何实际解决凸包?

python - 创建字典时“int”对象不可迭代

python - 将非空单元格移到 pandas DataFrame 的左侧

floating-point - pytorch 的机器精度是多少,什么时候应该使用 double ?

math - float 学有问题吗?