3

I want to colour both the 'Grand Total' row and the 'Total' column in a DataFrame object df, for which I tried the following:

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

However, when the compiler reaches the last line of the code, the following error arises:

---------------------------------------------------------------------------
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'

From what I understand, style.applymap() implicitly converts DataFrame into a Styler-type object, which cannot be further manipulated as a DataFrame.

Question 1: How can both rows and columns of a DataFrame object be coloured?

Question 2: How can a Styler-type object be converted into a DataFrame-type one?

V_B
  • 35
  • 1
  • 6
  • Also see [pandas styling](https://www.google.com/search?q=pandas+color+rows+site:stackoverflow.com&sxsrf=ALeKk03hi1m_tSuyftTaqnxtGulhTr_llw:1597186534853&sa=X&ved=2ahUKEwjj37LAn5TrAhXWJzQIHT8jB34QrQIoBHoECAEQBQ&biw=1920&bih=975) – Trenton McKinney Aug 11 '20 at 22:57
  • I don't think the question in the dup link solve the problem here. – Quang Hoang Apr 05 '22 at 00:34

1 Answers1

4

Style object returns an HTML-formatted string, so I don't think it's straight forward to turn it into a dataframe. Instead of applymap, I would rewrite the function so as it takes a column/row as argument and use apply. Something like this:

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)

Output:

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74