pandas style.bar颜色基于条件? [英] Pandas style.bar color based on condition?

查看:211
本文介绍了 pandas style.bar颜色基于条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何渲染Pandas df,其中根据某些条件计算列的style.bar.color属性之一?

How can I render a Pandas df where one of the columns' style.bar.color property is computed based on some condition?

示例:

df.style.bar(subset=['before', 'after'], color='#ff781c', vmin=0.0, vmax=1.0)

我不想让两列都用#ff781c突出显示,我希望其中一列(df['before'])保持相同的不变颜色,而另一列(df['after'])的计算方式为:

Instead of having both columns highlight with #ff781c, I'd like one of the columns (df['before']) to remain that same constant color, and the other column (df['after']) to be computed as:

def compute_color(row):
   if row['after'] >= row['before']:
      return 'red'
   else:
      return 'green

推荐答案

一种方法是使用pd.IndexSlicedf.style.bar创建子集:

One way to do is to use pd.IndexSlice to create subset for 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)

输出:

这篇关于 pandas style.bar颜色基于条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆