Suraj Sareen
Suraj Sareen

Reputation: 71

Conditional Formatting Pandas

I am trying to conditionally format a pandas dataframe and writing the output to excel. I am stuck at a point:

import pandas as pd
df = pd.DataFrame([['x',3,1],['x',2,2,],['y',4,6]],columns=list("ABC"))


def highlight_rows(row):
    value = row.loc['A']
    if value in ('x'):
        color = '#BAFFC9'
    else:
        color = None
return ['background-color: {}'.format(color) for r in row]



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

The above code will highlight all rows where the value in column A == 'x'. However, what I want to do is something like: if column A == 'x' then highlight column B else if column A == 'y' then highlight column C else None

I tried combining the above code by writing another function to highlight columns, but that does not seem to work.

def highlight_cols(col):
    if col.name == 'B':
        color = '#BAFFC9'
    else:
        color = None
return ['background-color: {}'.format(color) for c in col]

#Call to both the above functions is below

df.style.apply(highlightrows,axis=1).apply(highlight_cols,subset=['B])

Any pointers will be appreciated.

Upvotes: 1

Views: 533

Answers (1)

Nguyen
Nguyen

Reputation: 96

my approach is try to find each row and check value, column name for the highlight column. It should do the task.

import pandas as pd
df = pd.DataFrame([['x',3,1],['x',2,2,],['y',4,6]],columns=list("ABC"))

c_high= 'background-color: #BAFFC9'
def highlight_rows(row):
    lst = []
    value = row.loc['A']
    for col in row.index:
        if value in ('x') and col == 'B':
            lst.append(c_highlight)
            continue
        if value in ('y') and col == 'C':
            lst.append(c_highlight)
            continue
        lst.append(None)
    return lst

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

Upvotes: 1

Related Questions