3

如何渲染 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
4

2 回答 2

9

一种方法是使用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)

输出:

在此处输入图像描述

于 2019-08-20T21:08:01.920 回答
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

https://imgur.com/b2MHw8b

于 2020-07-08T16:36:13.817 回答