当我在舍入后将条形样式应用于 Pandas 数据框时,我丢失了舍入格式,并且我无法弄清楚如何应用舍入格式,因为 df.style.bar
不返回数据帧而是返回“样式器”对象。
df = pd.DataFrame({'A': [1.23456, 2.34567,3.45678], 'B':[2,3,4]})
df['A'] = df['A'].round(2)
df.style.bar(subset='A')
这返回但我不想显示所有这些额外的零。
最佳答案
您必须将样式器纯粹视为原始数据帧的渲染。这意味着您可以使用一种格式来显示四舍五入到小数点后两位的数据。
The basic idea behind styling is that a user will want to modify the way the data is presented but still preserve the underlying format for further manipulation.
f = {'A':'{:.2f}'} #column col A to 2 decimals
df.style.format(f).bar(subset='A')
阅读本文 excellent tutorial探索你可以用它做什么以及如何做。
编辑:添加了格式化字典以显示一般用途并将格式仅应用于单个列。
关于python - Pandas df.style.bar 同时保持四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65945695/