python - Pandas df.style.bar 同时保持四舍五入

标签 python pandas dataframe

当我在舍入后将条形样式应用于 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')
这返回
enter image description here
但我不想显示所有这些额外的零。

最佳答案

您必须将样式器纯粹视为原始数据帧的渲染。这意味着您可以使用一种格式来显示四舍五入到小数点后两位的数据。

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')
enter image description here
阅读本文 excellent tutorial探索你可以用它做什么以及如何做。
编辑:添加了格式化字典以显示一般用途并将格式仅应用于单个列。

关于python - Pandas df.style.bar 同时保持四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65945695/

相关文章:

python - 使用 Python 在 JIRA 中使用受让人、观察者和附件创建新问题

python - 如何使用 2 个 pandas DataFrame 计算 IOU(重叠)

python - 在 python 中使用数据框实现函数

python - 使用 pandas python reshape 为二进制变量

python - 无法迁移 Azure Django 应用程序的 Postgresql DB

python - 有没有办法在Python中使用super()来调用每个基类的__init__方法?

python - 使用 pandas groupby 或其他函数对多个数据帧进行子集化的简单方法?

pandas - matplotlib 条形图中的“缺失”条

python - 具有 Python 相关信息的前五名表

r - 使用 R 根据 VIF 标准自动从数据框中删除变量