python - 根据数据框中单元格中的值将颜色应用于单元格
问题描述
工作代码
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import numpy as np
from matplotlib import colors,cm
from matplotlib import pyplot as plt
filename = r'c:\Users\91956\Desktop\time_50.csv'
df = pd.read_csv(filename,index_col=0)
select_col = df.columns[1:]
cmap = mpl.colors.LinearSegmentedColormap.from_list("", ["red","white", "green"])
def background_gradient(s, cmap='PuBu', low=0, high=0):
s = pd.to_numeric(s, errors='coerce') #<-- here, string will become nan.
m = s.min() #<---------- here
M = s.max() #<-----------here
rng = M - m
norm = colors.TwoSlopeNorm(vmin=m - (rng * low), vcenter=0., vmax=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]
S = df.style.apply( background_gradient,
cmap=cmap,
low=0.5,
high=0.5,
subset= pd.IndexSlice[:, select_col],
axis=1
)
html = S.render()
with open("output.html","w") as fp:
fp.write(html)
我收到了这个错误
文件“c:\Users\91956\Desktop\asdf.py”,第 29 行,在 m=df.min().min() 中,文件“C:\Users\91956\AppData\Local\Programs\Python\Python39 \lib\site-packages\pandas\core\generic.py",第 11468 行,在 stat_func 中返回 self._reduce( 文件 "C:\Users\91956\AppData\Local\Programs\Python\Python39\lib\site-packages \pandas\core\series.py”,第 4248 行,在 _reduce 返回 op(delegate, skipna=skipna, **kwds) 文件“C:\Users\91956\AppData\Local\Programs\Python\Python39\lib\site -packages\pandas\core\nanops.py",第 129 行,在 f 结果 = alt(values, axis=axis, skipna=skipna, **kwds) 文件“C:\Users\91956\AppData\Local\Programs\ Python\Python39\lib\site-packages\pandas\core\nanops.py",第 873 行,减少结果 = getattr(values, meth)(axis) File "C:\Users\91956\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core_methods.py",第 43 行,in _amin 返回 umr_minimum(a, axis, None, out, keepdims, initial, where) TypeError:“numpy.ndarray”和“str”的实例之间不支持“>=”
更新 2 做了必要的更改。能够获得所需的输出。
解决方案
要创建示例 df:
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[3, 3] = np.nan
df.iloc[0, 2] = np.nan
from matplotlib import colors
cmap=LinearSegmentedColormap.from_list('rg',["r","w","g"], N=256)
def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
s = pd.to_numeric(s, errors='coerce') #<-- here, string will become nan.
print(s)
rng = M - m
norm = colors.DivergingNorm(vmin=m - (rng * low), vcenter=0., vmax=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]
x = df.apply(pd.to_numeric, errors='coerce') #<--- here string will be converted to `NaN` so that I can find out the max and min value.
df.style.apply(background_gradient,
cmap=cmap,
m=x.min().min(),
M=x.max().max(),
low=0.5,
high=0.5, subset=pd.IndexSlice[:, ['B', 'C']]
)
编辑:
通过subset=pd.IndexSlice[:, ['B', 'C']]
应用<--我想在列B
上应用颜色。C
df.style.apply(background_gradient,
cmap=cmap,
m=df.min().min(),
M=df.max().max(),
low=0.5,
high=0.5, subset=pd.IndexSlice[:, ['B', 'C']]
)
编辑2:
from matplotlib import colors
cmap=LinearSegmentedColormap.from_list('rg',["r","w","g"], N=256)
def background_gradient(s, cmap='PuBu', low=0, high=0):
s = pd.to_numeric(s, errors='coerce')
m = s.min() #<---------- here
M = s.max() #<-----------here
rng = M - m
norm = colors.DivergingNorm(vmin=m - (rng * low), vcenter=0., vmax=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]
# x = df.apply(pd.to_numeric, errors='coerce')
df.style.apply(background_gradient,
cmap=cmap,
low=0.5,
high=0.5, subset=pd.IndexSlice[:, ['B', 'C', 'D']], axis=1
)
在应用中使用axis=1
(沿着每行的列比较)
推荐阅读
- r - 如何用反引号作为字符串编码器和 ¥ 作为转义字符在 R 中读取 csv?
- vscode-tasks - 如何在vscode的python交互中杀死/停止正在运行的进程
- javascript - 将 https 添加到站点后,我的网页谷歌地图显示空白
- jquery - 单击一次后防止单击,直到用户再次单击另一个按钮
- python - 多边形图
- sql - Presto / Athena:如何在另一列上执行时间序列窗口函数时按一列的分类值分组?
- dataset - 匿名用户发布和共享链接后如何下载 Power BI 报表数据集
- mongodb - nginx背后的mongo图
- javascript - 如何在 Javascript 中设置 CSS 关键帧?
- javascript - 获取状态为 CMM Approved 的 jQuery 数据表的数据