gpt4 book ai didi

Python 3 破坏了 pandas 的渐变风格, 'SingleBlockManager' 是原因

转载 作者:行者123 更新时间:2023-12-01 02:02:01 25 4
gpt4 key购买 nike

从 python 2.7 迁移到 python 3.x,此代码破坏了源代码:

pandas style background gradient 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)

这是堆栈跟踪的最后一行:

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

最佳答案

显然,在 matplotlib 2.2 中您无法再使用数据帧调用 matplotlib.colors.Normalize

解决方案是使用数据帧的值来调用它,将 normed = s.apply(norm) 更改为

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

完整代码

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)

制作

enter image description here

关于Python 3 破坏了 pandas 的渐变风格, 'SingleBlockManager' 是原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com