Search code examples
pythonpandasjupyterpandas-styles

Highlight Cell with applymap doesn´t work in Jupyter


I'm trying highlight some cells on pivot_table, it depend of the value of the cell. When the value is over a 1000 the background color of the cell should be blue and red in other case.

I'm defining my color function

def color_range(val):
    background-color = 'blue' if val > 1000 else 'red'
    return 'background-color: %s' % background-color

And then I applied this function to my pivot_table

 df.style.applymap(color_range)
 df.head()

This code is not working, all cell are white. Maybe is the environment, I work in Jupyter.


Solution

  • df.style is not an inplace operation. Hence, what you see as output is second operation's output i.e df.head()


    To see the output of style, you would need to do

    df.style.applymap(color_range)
    

    However, if you want to see it on only for df.head() you could two ways

    df.head().style.applymap(color_range)
    

    Or, export the style, like

    style_bg = df.style.applymap(color_range)
    df.head().style.use(style_bg .export())