Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas style background gradient both rows and columns

Tags:

python

pandas

The pandas style option to add a background gradient is great for quickly inspecting my output table. However, it is applied either row-wise or columns-wise. Would it be possible to apply it to the whole dataframe at once?

EDIT: A minimum working example:

df = pd.DataFrame([[3,2,10,4],[20,1,3,2],[5,4,6,1]])
df.style.background_gradient()
like image 843
Peter9192 Avatar asked Aug 13 '16 10:08

Peter9192


3 Answers

Currently you can't set the background_gradient for both the rows/columns simultaneously as pointed by Nickil Maveli. The trick is to customize the pandas function background_gradient:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors

def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

df = pd.DataFrame([[3,2,10,4],[20,1,3,2],[5,4,6,1]])
df.style.apply(background_gradient,
               cmap='PuBu',
               m=df.min().min(),
               M=df.max().max(),
               low=0,
               high=0.2)
like image 149
Guilherme Beltramini Avatar answered Nov 07 '22 23:11

Guilherme Beltramini


You can use axis=None to get rid of the min and max computations in the call:

def background_gradient(s, m=None, M=None, cmap='PuBu', low=0, high=0):
    print(s.shape)
    if m is None:
        m = s.min().min()
    if M is None:
        M = s.max().max()
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = s.apply(norm)

    cm = plt.cm.get_cmap(cmap)
    c = normed.applymap(lambda x: colors.rgb2hex(cm(x)))
    ret = c.applymap(lambda x: 'background-color: %s' % x)
    return ret


df.style.apply(background_gradient, axis=None)

Edit: You may need to use normed = s.apply(lambda x: norm(x.values)) for this to work on matplotlib 2.2

like image 14
Andreas Mueller Avatar answered Nov 07 '22 22:11

Andreas Mueller


Setting axis=None is working for me in 1.0.5

like image 13
abogaard Avatar answered Nov 07 '22 21:11

abogaard