Styles

Contents

Styles#

It’s useful to have ability to highlight some cells depending on their content. This page focuses on how to do this in pandas and how to display it in jupyter notebook. To get more examples check out table visualisation on official pandas documentation.

import numpy as np
import pandas as pd

style.map#

It’s quite common to highlight large values with one colour and small values with another. This can be achieved with DataFrame.style.map. You have to pass a callable that is executed for each cell - it takes it’s value and returns a str that describes it’s property.


The following example shows how values higher than 0.5 are coloured red and others green.

sample_size = 10

def color_map(val):
    color = 'green' if val > 0.5 else 'red'
    return f'background-color: {color}'

pd.DataFrame({
    "a" : np.random.rand(sample_size),
    "b" : np.random.rand(sample_size)
}).style.map(color_map)
  a b
0 0.226920 0.928350
1 0.616279 0.656896
2 0.843329 0.346096
3 0.742186 0.490360
4 0.526169 0.478509
5 0.850815 0.920514
6 0.142186 0.083970
7 0.223666 0.769463
8 0.277761 0.451426
9 0.782243 0.078029

Gradients#

With Style.background_gradient, you can gradually change the background color of the cell, and with Style.text_gradient, you can apply a gradient effect to the text color within the cell.


The following cell demonstrates the application of these tools to the Pandas dataframe.

sample_size = 10

df = pd.DataFrame({
    "a" : np.random.rand(sample_size),
    "b" : np.random.rand(sample_size)
})

(
    df.sort_values("a").style
    .background_gradient(axis=0, cmap="RdYlGn", subset=["a"])
    .text_gradient(axis=0, subset="b")
)
  a b
3 0.001426 0.846427
5 0.045175 0.992176
1 0.096464 0.024943
7 0.207873 0.840228
0 0.225465 0.166648
8 0.523759 0.229616
2 0.654663 0.639400
4 0.718397 0.352168
9 0.962090 0.081076
6 0.978666 0.238494