1

Is it possible to add background color to column names while also changing cell background colors based on a separate condition?

I'm currently able to highlight cells based on a condition, but unsure how to add background color to column names:

# create dataframe 
import pandas as pd

data = {'Cuisine':['Italian','Indian','Nepalese','Mexican', 'Thai'],
   'Geographic Location':['Europe','Asia','Asia','N.America','Asia']}

df = pd.DataFrame(data) print(df)

    Cuisine Geographic Location
0   Italian              Europe
1    Indian                Asia
2  Nepalese                Asia
3   Mexican           N.America
4      Thai                Asia


# highlight cells based on condition
def highlight_Asia(x):
    return ['background-color: GreenYellow' if v =='Asia' else '' for v in x]

df.style.apply(highlight_Asia)

cells highlighted based on cond.

# highlight column names
def highlight_header(x):
    y= ['background-color: LightSkyBlue' for v in list(x)]
    return y

df.style.apply(highlight_header)

cant figure out how to highlight column names

Desired outcome:

desired outcome

References: 1 2

Mariah Akinbi
  • 386
  • 1
  • 5
  • 19

1 Answers1

0

You can use applymap(mapperFunc, subset=[ColOfInterest]) on your pandas style object, it will call the mapperFunc for each value in the pandas dataframe with the values passed, optionally you can pass selective columns using subset parameter.

Example code:

def color_me(percentage):
  color = 'green'
  if percentage < 40:
    color = 'red'

  return 'background-color: %s' % color

import pandas as pd
df = pd.DataFrame({'Marks' : range(0,101,20)})
df.style.applymap(color_me)

Output

enter image description here

VarunVk
  • 109
  • 2
  • 6