Revital Plotnikov
Revital Plotnikov

Reputation: 1

Apply styles to specific cells in Pandas Multindex Dataframe based on value comparison

I have a pandas multindex dataframe that looks something like this:

in [1] 
import pandas as pd
import numpy as np

iterables = [['Chemistry', 'Math', 'English'],['Semester_1', 'Semester_2']]
columns = pd.MultiIndex.from_product(iterables)
index = ['Gabby', 'Sam', 'Eric', 'Joe']
df = pd.DataFrame(data=np.random.randint(50, 100, (len(index), len(columns))), index=index, columns=columns)
df

out[1]
   Chemistry                  Math               English
  Semester_1 Semester_2 Semester_1 Semester_2 Semester_1 Semester_2
Gabby    86         80         63         50         87         75
Sam      57         84         91         84         60         87
Eric     67         64         52         96         84         70
Joe      51         68         74         69         85         86

I am trying to see if there were students who's grades dropped in more than 10 points in the last semester, color the cells containing the bad grade red and export the whole table to excel. For example, Gabby's Math grade in the second semester dropped 13 points, so I would like the cell containing "50" to be colored red. Here is the full output I'm expecting.

I have tried the following:

def color_values(row):
    change = row['Semester_1'] - row['Semester_2']
    color = 'red' if change > 10 else ''
    return 'color: ' + color

for subject in ['English', 'Algebra', 'Geometry']:
    df = df.style.apply(color_values, axis=1, subset=[subject])

However I'm getting the following error:

AttributeError                            Traceback (most recent call last)
<ipython-input-5-e83756bce6ef> in <module>
      1 for subject in ['English', 'Algebra', 'Geometry']:
----> 2     df = df.style.apply(color_values, axis=1, subset=[subject])

AttributeError: 'Styler' object has no attribute 'style'

I cannot figure out a way to do this. Please help.

Upvotes: 0

Views: 61

Answers (1)

Attack68
Attack68

Reputation: 4785

in your first loop when subject is "English" you are setting df to be a Styler object, e.g. df.style.

The in your second loop you are calling .style on df which you set as a Styler object, hence the AttributeError.

styler = df.style
for subject in ['English', 'Algebra', 'Geometry']:
    styler.apply(color_values, axis=1, subset=[subject])

Upvotes: 0

Related Questions