如何渲染Pandas df,其中根据某些条件计算列的style.bar.color
属性之一?
示例:
df.style.bar(subset=['before', 'after'], color='#ff781c', vmin=0.0, vmax=1.0)
我不想让两列都用#ff781c
突出显示,我希望其中一列(df['before']
)保持相同的不变颜色,而让另一列(df['after']
)保持不变计算为:
def compute_color(row):
if row['after'] >= row['before']:
return 'red'
else:
return 'green
答案 0 :(得分:4)
一种方法是使用pd.IndexSlice
为df.style.bar
创建子集:
i_pos = pd.IndexSlice[df.loc[(df['after']>df['before'])].index, 'after']
i_neg = pd.IndexSlice[df.loc[~(df['after']>df['before'])].index, 'after']
df.style.bar(subset=['before'], color='#ff781c', vmin=0.0, vmax=1.0)\
.bar(subset=i_pos, color='green', vmin=0.0, vmax=1.0)\
.bar(subset=i_neg, color='red', vmin=0.0, vmax=1.0)
输出:
答案 1 :(得分:0)
为列中的每个单元格明确着色。
rows = 10
indx = list(df.index)[-rows:] # indices of the last 10 rows
# Colormap for the last 10 rows in a Column
last10 = df['Column'][-rows:] # values to color
colors = [color_map_color(e, cmap_name='autumn_r', vmin=100, vmax=1000) for e in last10] # colors
values = [pd.IndexSlice[indx[i], 'Column'] for i in range(rows)] # for .bar subset
html = (df.style
.bar(subset=values[0], color=colors[0], vmax=1000, vmin=0, align='left', width=100)
.bar(subset=values[1], color=colors[1], vmax=1000, vmin=0, align='left', width=100)
.bar(subset=values[2], color=colors[2], vmax=1000, vmin=0, align='left', width=100)
)
html