3

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

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

is there a solution that doesn't involve .apply(..., axis=1), i found that this op isn't very performant for very large dataframe.
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

4 Comments

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 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
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.
How can i do it for multiple columns at a time ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.