使用 Styler 对数据框着色后格式化数字

gar*_*ous 4 python formatting dataframe pandas pandas-styles

我在 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

Run Code Online (Sandbox Code Playgroud)

返回

在此输入图像描述

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

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

Jak*_*kub 11

看看pandas 造型指南。该df.style属性返回一个Styler实例,而不是数据帧。从 pandas 样式指南中的示例来看,似乎数据帧操作(如舍入)是首先完成的,样式是最后完成的。pandas 样式指南中有一个关于精度的部分。该部分提出了三种不同的选项来显示值的精度。

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 .format() method of styler.
style = df.style.format(precision=2).background_gradient(cmap='RdYlGn')
style
Run Code Online (Sandbox Code Playgroud)