2

I have applied pandas on an excel file and below is the dataframe :

      Name  Count
0   Name 1     75
1   Name 2     55
2   Name 3     50
3   Name 4     47
4   Name 5     43
5   Name 6     42
6   Name 7     35
7   Name 8     34
8   Name 9     32
9   Name 10    16
10  Name 11     6
11  Name 12     3
12  Name 13     1
13  Name 14     1
14    Total   440

I have to apply conditional formatting on above data frame and convert in to html.

I followed style "http://pandas.pydata.org/pandas-docs/stable/style.html#Building-Styles" for this and did below :

def change_colour(val):
   return ['background-color: red' if x < 40 else 'background-color: green' for x in val]

name_column_html_1 = final_name_df.style.apply(change_colour, axis=1, subset=['Count'])
print(name_column_html_1.render())

This is the output I am getting from above code

This is the output I am getting

How can i get output like below ?

How can i output like this

avinashse
  • 1,440
  • 4
  • 30
  • 55

2 Answers2

10

You use df.style.apply

def row_style(row):
    if row.Name != 'Total':
        if row.Count < 40:
            return pd.Series('background-color: red', row.index)
        else:
            return pd.Series('background-color: green', row.index)
    else:
        return pd.Series('', row.index)

df.style.apply(row_style, axis=1)

enter image description here

piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • is there a solution that doesn't involve .apply(..., axis=1), i found that this op isn't very performant for very large dataframe. – kawingkelvin Dec 09 '21 at 22:43
5

I think you can add one more condition here

def change_colour(val):
   return ['background-color: red' if x < 40  else ('' if x==440 else 'background-color: green') for x in val]

name_column_html_1 = final_name_df.style.apply(change_colour, axis=1, subset=['Count'])

enter image description here

BENY
  • 317,841
  • 20
  • 164
  • 234
  • Thanks wen for reply, but the output i am looking is to change the color of name column as well with the color of count column – avinashse Apr 10 '18 at 04:56
  • @avinashse you can change to this `def change_colour(x): df = x.copy() m1 = (df['Count'] < 40)&(df['Count'] !=440) df.loc[m1, :] = 'background-color: red' df.loc[~m1,:] = 'background-color: green' return df ` – BENY Apr 10 '18 at 05:10
  • Thank you, but getting error : pandas.core.indexing.IndexingError: ((False, slice(None, None, None)), 'occurred at index 0'), `x.copy()` is returning series, i think that is why. – avinashse Apr 10 '18 at 05:26
  • How can i do it for multiple columns at a time ? – raj Oct 28 '19 at 09:06