使用 Styler 为数据框着色后格式化数字 (pandas)

Formatting numbers after coloring dataframe using Styler (pandas)

我在 pandas 中创建了一个 DataFrame,我想使用颜色索引(低值红色,高值绿色)为单元格着色。我成功地这样做了,但是着色阻止我格式化单元格。

import pandas as pd

df = pd.DataFrame({'a': [0.5,1.5, 5],
                   'b': [2, 3.5, 7] })

df = df.style.background_gradient(cmap='RdYlGn')
df

哪个returns

但是,当我尝试使用 df.round(2) 来格式化数字时,弹出以下错误:

AttributeError: 'Styler' object has no attribute 'round'

有谁能告诉我这是怎么回事吗?

查看 pandas 样式指南中的 pandas styling guide. The df.style property returns a Styler instance, not a dataframe. From the examples in the pandas styling guide, it seems like dataframe operations (like rounding) are done first, and styling is done last. There is a section on precision。该部分提出了三种不同的选项来显示值的精度。

import pandas as pd

df = pd.DataFrame({'a': [0.5,1.5, 5],
                   'b': [2, 3.5, 7] })

# Option 1. Round before using style.
style = df.round(2).style.background_gradient(cmap='RdYlGn')
style

# Option 2. Use option_context to set precision.
with pd.option_context('display.precision', 2):
    style = df.style.background_gradient(cmap='RdYlGn')
style

# Option 3. Use .set_precision() method of styler.
style = df.style.background_gradient(cmap='RdYlGn').set_precision(2)
style