Skip to content
Advertisement

Highlight rows from a DataFrame based on values in a column in Python Pandas

I have been trying to highlight some rows in a pandas dataframe based on multiple conditions.

I’m expecting that when a string in the target column match the criteria defined in the function, the entire row will be highlighted.

I tried different combinations of the .style.apply method, but it kept giving me the following error:

ValueError: style is not supported for non-unique indicies.

This is the code:

def highlight_rows(s):        
    if s['my_column'] == 'some_text':
        return 'background-color: green'
    elif s['my_column'] == 'somedifferent_text':
        return 'background-color: blue'

df.style.apply(highlight_rows, axis = 0)

I’m using Python 3.6.5 and Pandas 0.22.0

Any idea on what I’m doing wrong?

Should I pass different parameters or doing a different loop?

Thank you

Advertisement

Answer

The apply method extracts each column or row depend on axis=0 or axis=1. Then you can add any style for each cell in rows or columns. If you want to pass your style through method, you need to assign the method expression for each element of array. Otherwise, it must be None value.

def highlight_rows(s):
    con = s.copy()
    con[:] = None
    if (s['my_column'] == 'some_text'):
        con[:] = "background-color: green"
    elif (s['my_column'] == 'somedifferent_text'):
        con[:] = "background-color: blue"
    return con
        
df.style.apply(highlight_rows, axis=1)
Advertisement