Home > Net >  How to style pandas dataframe using for loop
How to style pandas dataframe using for loop

Time:12-21

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)

CodePudding user response:

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)

CodePudding user response:

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))
  • Related