Python 基于dataframe中单元格中的值对单元格应用颜色

Python 基于dataframe中单元格中的值对单元格应用颜色,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,工作代码 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)

工作代码

 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)
将熊猫作为pd导入
导入seaborn作为sns
将matplotlib导入为mpl
将numpy作为np导入
从matplotlib导入颜色,cm
从matplotlib导入pyplot作为plt
filename=r'c:\Users\91956\Desktop\time\u 50.csv'
df=pd.read\u csv(文件名、索引\u col=0)
选择列[1:]
cmap=mpl.colors.LinearSegmentedColormap.from_列表(“,[“红色”,“白色”,“绿色])
def背景梯度(s,cmap='PuBu',低=0,高=0):
s=pd.to_numeric(s,errors='concurve')#这将有所帮助,也会有所帮助

要创建示例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

编辑2:
从matplotlib导入颜色
cmap=LinearSegmentedColormap。从_列表('rg',[“r”,“w”,“g”],N=256)
def背景梯度(s,cmap='PuBu',低=0,高=0):
s=pd.to_numeric(s,errors='concurve')

m=s.min()#问题是您的值范围的中值不是零。调用
background\u gradient
时,尝试设置
low,high
什么应该是high和low,以使零成为中间值,例如low=-5和high=5这样的值?它不起作用。我已经更新了我的答案@AniketPatil:检查它现在起作用了。正常值是多少(s.values)@AniketPatil:s是数据帧df的元素SPASS
subset=pd.indexlice[:,['B','C']]
检查编辑后的答案。也可以使用此列选择行,或仅选择要传递的列。可以将列名列表传递给子集。您可以根据您的需要修改此代码:)我正在使用的df如图所示,它包含str数据以及ticker列,我试图修改我的代码,但无法获得所需的输出,我已使用代码更新了问题,我正在使用非常完整的答案!美好的
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']]
              )
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']]
              )
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
              )