Search code examples
pythonpython-3.xpandaspandas-styles

Using iloc with pandas styler


I currently have:

def color_cell(val):
    color = 'lightgreen' if val ==0 else 'white'
    return 'background-color: %s' % color

s = df.style.applymap(color_cell)

Which gives the following dataframe:

enter image description here

I want to use pandas.dataframe.iloc to cherry pick which values are highlighted. For instance use df.iloc[0,1] and df.iloc[1,2] so that only these values are highlighted.

How can I update this code?


Solution

  • "Only label-based slicing is supported right now, not positional." see the docs

    A work around could looks like this:

    # sample data
    np.random.seed(1)
    df = pd.DataFrame({'col':np.random.randint(0,4,5),
                       'col1':np.random.randint(0,4,5),
                       'col2':np.random.randint(0,4,5)})
    
    def color_cell(df):
        return 'background-color: lightgreen'
    
    df.style.applymap(color_cell, subset=(0,'col')).applymap(color_cell, subset=(1,'col2'))
    

    enter image description here