Okorimi Manoury
Okorimi Manoury

Reputation: 134

condionally color text in python

Is it possible to display each word with its color with python? We have an example of words with their colors:

    Mots             Poids      colors
 0  un              0.000007    #39e600
 1  bon             0.000005    #d9ffcc
 2  rapport         0.000009    #39e600
 3  qualité/prix.   0.000014    #269900

thank you in advance.

Upvotes: 1

Views: 71

Answers (1)

jpp
jpp

Reputation: 164623

Using Pandas, it is possible to style a series for display in, for example, Jupyter notebook.

Here's an example:

df = pd.DataFrame({'Mots': ['un', 'bon', 'rapport', 'qualité/prix.'],
                   'colors': ['#39e600', '#d9ffcc', '#39e600', '#269900']})

def map_colors(x):
    df1 = x.copy()
    df1.loc[:, 'Mots'] = 'background-color: ' + df1.loc[:, 'colors']
    df1.loc[:, 'colors'] = 'background-color: '
    return df1

res = df.style.apply(map_colors, axis=None)

Result

enter image description here

Upvotes: 1

Related Questions