【问题标题】:How to colour rows in a dataframe using style.applymap()? [duplicate]如何使用 style.applymap() 为数据框中的行着色? [复制]
【发布时间】: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


【解决方案1】:

Style 对象返回一个 HTML 格式的字符串,所以我认为将其转换为数据框并不容易。我将重写函数而不是applymap,以便它以列/行作为参数并使用apply。像这样的:

def bg_colour_col (col):
    colour = '#ffff00'
    return ['background-color: %s' % colour 
                if col.name=='Total' or i==4   # color column `Total` or row `4`
                else ''
             for i,x in col.iteritems()]

df.style.apply(bg_colour_col)

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多