Home > OS >  How to apply conditional color styling to a column in a Multi-index pandas dataframe
How to apply conditional color styling to a column in a Multi-index pandas dataframe

Time:06-03

I already had a question answered for conditionally applying color with a normal Dataframe. enter image description here

I tried replacing row['Limit'] with x.loc[:,idx[:,'Limit']] where idx is pd.IndexSlice but it did not work

import re

def highlight(row):
    numbers = re.findall('[0-9] ', row['Limit'])
    if row['Value'] in ('Issues','Rating','Complaints'):
        if '>' in row['Limit'] and row['Actual'] > numbers[0]:
            color = 'green'
        elif row['Actual'] < numbers[0]:
            color = 'green'
        else:
            color = 'red'
    else:
        if len(numbers) == 0:
            color = 'yellow'
        elif row['Actual'] > numbers[0] and row['Actual'] < numbers[1]:
            color = 'green'
        else:
            color = 'red'
    return f"background-color: {color}"

CodePudding user response:

You need change:

row['Limit']

to:

row[('summary', 'Limit')]

for select by MultiIndex in columns.

EDIT:

If use:

row[(slice(None),'Limit')]
row[idx[:,'Actual']]

output is one element Series.

So need select first value in this methods for scalar:

row[(slice(None),'Limit')].iat[0]
row[idx[:,'Actual']].iat[0]
  • Related