Search code examples
pythonpandasbooleanhighlight

Highlight row based on boolean column


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


Solution

  • 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