[英]Python: Color pandas dataframe based on MultiIndex
考慮這個 MultiIndex 數據框
i = pd.MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0), (1, 1)], names=['level_0', 'level_1'])
df = pd.DataFrame(range(0, 4), index=i, columns=['foo'])
還有這本彩色詞典
colors = {0: (0.6, 0.8, 0.8, 1), 1: (1, 0.9, 0.4, 1)}
其中元組的前三項是 RGB 值,第四項是透明度 alpha。
如何根據 level_0 索引對 df 進行着色?
這個結果會很好:
但這里的這個我會考慮美術:
在后一種樣式中,較亮的單元格將具有相同的 RGB 設置,但透明度為 0.25。
您可以使用Styler.set_table_styles
來設置Styler.set_table_styles
的第一級MultiIndex
:
i = pd.MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0), (1, 1)], names=['level_0', 'level_1'])
df = pd.DataFrame(range(0, 4), index=i, columns=['foo'])
#print (df)
import matplotlib.colors as col
colors = {0: (0.6, 0.8, 0.8, 1), 1: (1, 0.9, 0.4, 1)}
c = {k:col.rgb2hex(v) for k, v in colors.items()}
idx = df.index.get_level_values(0)
css = [{'selector': f'.row{i}.level0','props': [('background-color', c[v])]}
for i,v in enumerate(idx)]
print (css)
df.style.set_table_styles(css)
第二種也是可能的,但更復雜:
colors = {0: (0.6, 0.8, 0.8, 1), 1: (1, 0.9, 0.4, 1)}
#converts grba to integers
c1 = {k: (int(r * 255),int(g * 255),int(b * 255), a) for k, (r,g,b,a) in colors.items()}
c2 = {k: (int(r * 255),int(g * 255),int(b * 255), 0.25) for k, (r,g,b,a) in colors.items()}
#get values of first level of MulitIndex
idx = df.index.get_level_values(0)
#set css for first level
css = [{'selector': f'.row{i}.level0',
'props': [('background-color', f'rgba{c1[j]}')]} for i,j in enumerate(idx)]
#counter per first level for pair and unpair coloring
zipped = zip(df.groupby(idx).cumcount(), enumerate(idx))
css1 = [{'selector': f'.row{i}', 'props': [('background-color', f'rgba{c1[j]}')]}
if v % 2 == 0
else {'selector': f'.row{i}', 'props': [('background-color', f'rgba{c2[j]}')]}
for v,(i, j) in zipped]
df.style.set_table_styles(css1 + css)
@jezrael 已經完成了藝術!
import pandas as pd
i = pd.MultiIndex.from_tuples([(0, 'zero'), (0, 'one'), (0, 'two'), (1, 'zero'), (1, 'one')], names=['level_0', 'level_1'])
df = pd.DataFrame(range(0, 5), index=i, columns=['foo'])
colors = {0: (0.6, 0.8, 0.8, 1), 1: (1, 0.9, 0.4, 1)}
#convert rgba to integers
c1 = {k: (int(r * 255),int(g * 255),int(b * 255), a) for k, (r,g,b,a) in colors.items()}
c2 = {k: (int(r * 255),int(g * 255),int(b * 255), 0.25) for k, (r,g,b,a) in colors.items()}
#get values of first level of MulitIndex
idx = df.index.get_level_values(0)
#counter per first level for pair and unpair coloring
zipped = zip(df.groupby(idx).cumcount(), enumerate(idx))
css = [{'selector': f'.row{i}', 'props': [('background-color', f'rgba{c1[j]}')]}
if v % 2 == 0
else {'selector': f'.row{i}', 'props': [('background-color', f'rgba{c2[j]}')]}
for v,(i, j) in zipped]
df.style.set_table_styles(css)
與@jezrael 的解決方案相比,以上內容更短。
我也喜歡該解決方案不依賴於有序整數的索引標簽。 請注意,我使用的是字符串(至少對於第二個索引級別)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.