【发布时间】:2020-12-01 15:55:38
【问题描述】:
我想为 DataFrame 对象df 中的“Grand Total”行和“Total”列着色,为此我尝试了以下操作:
import pandas as pd
# Function to set background highlight colour.
def bg_colour (val):
colour = '#ffff00'
return 'background-color: %s' % colour
df = pd.DataFrame({'Category': ['A','B','C','D','Grand Total'], 'Total': [1,2,3,4,10]})
t1 = df.style.applymap(bg_colour, subset = ['Total'])
dfT = df.T
dfT = dfT.style.applymap(bg_colour, subset = [4])
t1T = t1.T
但是,当编译器到达代码的最后一行时,会出现以下错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-48-c0c380b9c518> in <module>
12 dfT = dfT.style.applymap(bg_colour, subset = [4])
13 display(dfT)
---> 14 t1T = t1.T
AttributeError: 'Styler' object has no attribute 'T'
据我了解,style.applymap() 隐式将 DataFrame 转换为 Styler 类型的对象,无法将其作为 DataFrame 进一步操作。
问题 1:如何对 DataFrame 对象的行和列进行着色?
问题 2:如何将 Styler 类型的对象转换为 DataFrame 类型的对象?
【问题讨论】:
标签: python pandas dataframe colors rows