Search code examples
pythonpandasconditional-formattingpandas-styles

How to conditionally format pandas row groups in jupyter


I have a dataframe in pandas that looks a bit like this:

A     B     C
1     0.5   0.6
1     0.7   0.1
2     0.3   0.2
3     0.1   0.3
3     0.2   0.1

When you print a pandas dataframe in jupyter, the default output style is to color each row using alternating light and grey backgrounds. I would like to be able to adjust the background color of each group of column A values so that each group has an alternating color scheme. So similar to the default style, except instead of each row background alternating grey and white, it would alternate by groups of values from column A.

I found some documentation here:https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html. I'm unsure how to apply the methods there to this end as they all seem to either only interact with a cell element or only interact with one particular row.


Solution

  • Try this:

    def change_color_group(x):
        df = x.copy()
        df.loc[df['A'] == 1, :] = 'background-color: yellow'
        df.loc[df['A']==2,:] = 'background-color: red'
        df.loc[df['A']==3, :] ='background-color: blue'
        return df  
    
    
    df.style.apply(change_color_group, axis=None)
    

    enter image description here