我在 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
哪个返回
但是,当我尝试使用 df.round(2)
来格式化数字时,会弹出以下错误:
AttributeError: 'Styler' object has no attribute 'round'
谁能告诉我出了什么问题?
答案 0 :(得分:1)
看看 pandas styling guide。 df.style
属性返回一个 Styler
实例,而不是数据帧。从 pandas 样式指南中的示例来看,似乎首先完成数据帧操作(如舍入),最后完成样式。 pandas 样式指南中有 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