1

Have a dataframe for which I've created the boolean column 'Late Submission', where 'True' means it was late and 'False' is on-time.

I want to highlight 'True' rows in red and 'False' in green but I can't seem to get it working as I'm still pretty new to Python. I've tried the code below, any ideas why it's not working?

def highlight_late(s):
    if s['Late Submission'] == True:
        return 'background-color: red'
    elif s['Late Submission'] == False:
        return 'background-color: green'
    
df7.style.apply(highlight_late, axis = 1)

The error given is:

Result has shape: (281556,)
Expected shape:   (281556, 6)

Thanks in advance

1
  • According to the API doc, func should take a Series or DataFrame (depending on axis), and return an object with the same shape. Your func returns a scalar. Commented Mar 9, 2021 at 15:38

2 Answers 2

3

To borrow the sample df from Albo. If you want to color the entire row, you can adapt the code to:

def highlight_late(s):
    return ['background-color: red' if s['late'] else 'background-color: green' for s_ in s]

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

Which will give you:

enter image description here

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

Comments

2

I used this simple df to show how it works, based on this pandas doc

import pandas as pd
import numpy as np
df = pd.DataFrame({'a': np.random.randint(0, 10, 10), 'b': np.random.randint(0, 10, 10), 'late': np.random.choice([0, 1], 10).astype(np.bool)})

this gives us:

|    |   a |   b | late   |
|---:|----:|----:|:-------|
|  0 |   3 |   2 | False  |
|  1 |   1 |   0 | False  |
|  2 |   3 |   6 | False  |
|  3 |   0 |   1 | True   |
|  4 |   6 |   7 | True   |
|  5 |   0 |   0 | False  |
|  6 |   0 |   7 | False  |
|  7 |   6 |   4 | True   |
|  8 |   7 |   0 | True   |
|  9 |   7 |   7 | False  |

Now we use a function to apply the style:

def highlight_late(s):
    return ['background-color: red' if s_ else 'background-color: green' for s_ in s]

and then:

df.style.apply(highlight_late, subset=['late'])

results in:

enter image description here

Comments

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.