Pandas style.bar color based on condition?

ⅰ亾dé卋堺 提交于 2020-06-26 08:44:51

问题


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

Example:

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

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

回答1:


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)

Output:



来源:https://stackoverflow.com/questions/57580589/pandas-style-bar-color-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!