首页 > 解决方案 > 根据数据框中单元格中的值将颜色应用于单元格

问题描述

在此处输入图像描述

工作代码

 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 做了必要的更改。能够获得所需的输出。

在此处输入图像描述

标签: pythonpandasmatplotlibseaborn

解决方案


这个答案和这个答案都会有所帮助。

要创建示例 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(沿着每行的列比较)


在此处输入图像描述


推荐阅读