Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to style pandas dataframe using for loop

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading