[英]How to change background cell color according with a given key in pandas?
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']
)
由Antonvbr更新:(受此解决方案的影响,我也添加了一个使用seaborn的解决方案)。
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']
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.