Python 3 break pandas style for gradients, "SingleBlockManager" - reason

Migrating from python 2.7 to python 3.x, this code is interrupted Source:

pandas background gradient style of both rows and columns

import pandas as pd import matplotlib.pyplot as plt from matplotlib import colors 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 = pd.DataFrame([[3,2,10.3,4],[20,1,3.5,2],[5,4,6.9,1]]) df.style.apply(background_gradient, axis=None) 

This is the last line of the stack trace:

 TypeError: ("float() argument must be a string or a number, not 'SingleBlockManager'", 'occurred at index 0') 
+1
source share
1 answer

Apparently you can no longer call matplotlib.colors.Normalize with a dataframe in matplotlib 2.2.

The solution was to call it using dataframe values, changing normed = s.apply(norm) to

  normed = s.apply(lambda x: norm(x.values)) 

Full code

 import pandas as pd import matplotlib.pyplot as plt from matplotlib import colors def background_gradient(s, m=None, M=None, cmap='PuBu', low=0, high=0): if m is None: m = s.min().min() if M is None: M = s.max().max() rng = M - m norm = colors.Normalize(m ,M) normed = s.apply(lambda x: norm(x.values)) 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 = pd.DataFrame([[3,2,10.3,4],[20,1,3.5,2],[5,4,6.9,1]]) df.style.apply(background_gradient, axis=None) 

production

enter image description here

+2
source

All Articles