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

Change colors for values in pandas column list

Hello everyone I have a dataframe:

df = pd.DataFrame({
    'list_text': [['t4', 't5', 't6'], ['t7', 't1', 't2', 't3']],
    'list_userid': [['u1', 'u2', 'u4'], ['u3']],
    'list_date': [['2021-01', '2021-02'], ['2021-01']]
})

and I want to change the color in the list_text column for each value. That is, the first value is red, then blue, etc. and everything is in the list and so for each row.
Is this even possible to do?

For example something like this:

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

enter image description here

>Solution :

You can try to generate yourself the HTML, then convert to_html without escaping:

from IPython.display import display, HTML

colors = ['#9FE2BF', '#DE3163', '#FFBF00', '#6495ED']

display(HTML(
  df.assign(list_text=['['+', '.join([f'<span style="color:{c}";>{v}</span>'
                                     for c, v in zip(colors, l)])+']'
                       for l in df['list_text']]
            )
    .to_html(escape=False)
))

NB. note that zip stops with the shortest iterable, ensure to have enough colors in colors. Alternatively, use itertools.zip_longest with a default color.

Output:

pandas Series of list with different color for each word

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