0

For rows in a pandas dataframe that have a given value in a given column, I cannot figure out how to make those rows both colored yellow and bold type.

The following coding successfully colors a row based on a column value. Or it can be used to successfully bold type a row based on a column value. The following is based on this link by Stephen.

import pandas as pd

df = pd.DataFrame({"A" : [14, 4, 5, 4, 1],
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8], 
                   "D" : [14, 3, 6, 2, 6],
                   "E" : [23, 45, 64, 32, 23]}) 

def highlight(s):
    if s.C == 7:
        return ['background-color: yellow'] * len(s)                             # this works
        # return ['font-weight: bold'] * len(s)                                    # this works
        # return [{'background-color: yellow' & 'font-weight: bold'}] * len(s)     # this fails
        # return [('background-color: yellow') & ('font-weight: bold')] * len(s)   # this fails
        # return [{('background-color: yellow') & ('font-weight: bold')}] * len(s) # this fails
    else:
        return ['background-color: white'] * len(s)

df.style.apply(highlight, axis=1)

Hopefully this is an image of the output.

I cannot figure out how to make the row where df.C == 7 both colored and bold.

raml5
  • 3
  • 2

1 Answers1

0

You can do this to get the desired result.

You can include both color and font with a semicolon:

return ['background-color: yellow; font-weight: bold'] * len(s)

The full code is here:

import pandas as pd

df = pd.DataFrame({"A" : [14, 4, 5, 4, 1],
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8], 
                   "D" : [14, 3, 6, 2, 6],
                   "E" : [23, 45, 64, 32, 23]}) 

def highlight(s):
    if s.C == 7:
        return ['background-color: yellow; font-weight: bold'] * len(s)  # this works
    else:
        return ['background-color: white'] * len(s)
    
df.style.apply(highlight, axis=1)

I removed all the other code you used (not required anymore):

        # return ['font-weight: bold'] * len(s)                                    # this works
        # return [{'background-color: yellow' & 'font-weight: bold'}] * len(s)     # this fails
        # return [('background-color: yellow') & ('font-weight: bold')] * len(s)   # this fails
        # return [{('background-color: yellow') & ('font-weight: bold')}] * len(s) # this fails

Your output will be:

enter image description here

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33