Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

python - How to change background cell color according with a given key in pandas?

I have the following dataframe:

df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"],  
                   "B":["A","A","B","A"], 
                   "C":[0,3,1,1]})

How can I change the cell color of columns A and B, grouped by its values. I mean, this would be the desirable output:

enter image description here

Maybe something like:

df.groupby(by=['A', 'B']).style.change_background()

As the real dataframe has hundreds of rows, I'd be interestested in assigning the colors automatically.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
from matplotlib.pyplot import cm 
from matplotlib.colors import to_hex

# convert groups to indices    
g = pd.Categorical(df.A + df.B).codes

# generate a list hex colors
color = cm.rainbow(g / g.max())
hex_color = [to_hex(col) for col in color]
print('generate colors: ', hex_color)

# apply the colors to style for columns A and B
df.style.apply(
    lambda col: ['background-color: %s' % (hex_color[i]) for i in range(col.size)], 
    subset=['A', 'B']
)

enter image description here

Update by Antonvbr: (Insipred by this solution I added a solution using seaborn too).

import seaborn as sns
import pandas as pd

df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"],  
                   "B":["A","A","B","A"], 
                   "C":[0,3,1,1]})

g = pd.Categorical(df.A + df.B).codes # convert groups to indices  
n = np.unique(g).size
palette = sns.color_palette("hls", n).as_hex()

# apply the colors to style for columns A and B
df.style.apply(
    lambda x: ['background-color: {}'.format(palette[i]) for i in g], 
    subset=['A', 'B']
)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...