rodrigo-silveira
rodrigo-silveira

Reputation: 13078

Pandas style.bar color based on condition?

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)

enter image description here

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

Upvotes: 3

Views: 5726

Answers (2)

khnh123
khnh123

Reputation: 41

Explicitly color each cell in column.

    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://i.sstatic.net/FeUV0.jpg

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153460

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:

enter image description here

Upvotes: 9

Related Questions