How to style pandas dataframe using for loop

Question:

I have a dataset where I need to display different values with different colors. Not all the cells in the data are highlighted and only some of the data is highlighted.

Here are some of the colors:
dict_colors = {‘a’: ‘red’, ‘b’: ‘blue’,’e’:’tomato’}

How can I highlight all these cells with given colors?

MWE

# data
import pandas as pd
df = pd.DataFrame({'A': list('abcdef'), 'B': list('aabbcc'), 'C': list('aaabbb')})

# without for loop
(df.style
  .apply(lambda dfx: ['background: red' if val == 'a' else '' for val in dfx], axis = 1)
  .apply(lambda dfx: ['background: blue' if val == 'b' else '' for val in dfx], axis = 1)
)

# How to do this using for loop (I have so many values and different colors for them)
# My attempt

dict_colors = {'a': 'red', 'b': 'blue','e':'tomato'}
s = df.style

for key,color in dict_colors.items():
    s = s.apply(lambda dfx: [f'background: {color}' if cell == key else '' for cell in dfx], axis = 1)

display(s)
Asked By: dallascow

||

Answers:

I found a way using eval method, it is not the most elegant method but it works.

import pandas as pd

df = pd.DataFrame({'A': list('abcdef'), 'B': list('aabbcc'), 'C': list('aaabbb')})

dict_colors = {'a': 'red', 'b': 'blue','e':'tomato'}

lst = [ 'df.style']

for key,color in dict_colors.items():
    text = f".apply(lambda dfx: ['background: {color}' if cell == '{key}' else '' for cell in dfx], axis = 1)"
    lst.append(text)

s = ''.join(lst)
display(eval(s))
Answered By: dallascow

You can try that:

import pandas as pd


df = pd.DataFrame({'A': list('abcdef'), 'B': list('aabbcc'), 'C': list('aaabbb')})


dict_colors = {'a': 'red', 'b': 'blue', 'e':'tomato'}

# create a Styler object for the DataFrame
s = df.style

def apply_color(val):
    if val in dict_colors:
        return f'background: {dict_colors[val]}'
    return ''

# apply the style to each cell
s = s.applymap(apply_color)

# display the styled DataFrame
display(s)
Answered By: Vagner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.