Python Pandas style.background_渐变忽略NaN

Python Pandas style.background_渐变忽略NaN,python,pandas,seaborn,Python,Pandas,Seaborn,我有以下代码将数据帧结果转储到HTML表格中,这样时间帧中的列将根据seaborn提供的颜色映射进行着色 import seaborn as sns TIME_FRAMES = ["24h", "7d", "30d", "1y"] # Set CSS properties for th elements in dataframe th_props = [ ('font-size', '11px'), ('text-align', 'center'), ('font-w

我有以下代码将数据帧
结果
转储到HTML表格中,这样
时间帧
中的列将根据seaborn提供的颜色映射进行着色

import seaborn as sns

TIME_FRAMES = ["24h", "7d", "30d", "1y"]

# Set CSS properties for th elements in dataframe
th_props = [
    ('font-size', '11px'),
    ('text-align', 'center'),
    ('font-weight', 'bold'),
    ('color', '#6d6d6d'),
    ('background-color', '#f7f7f9')
]

# Set CSS properties for td elements in dataframe
td_props = [
    ('font-size', '11px')
]


cm = sns.light_palette("green", as_cmap=True)
s = (results.style.background_gradient(cmap=cm, subset=TIME_FRAMES)
                  .set_table_styles(styles))
a = s.render()
with open("test.html", "w") as f:
    f.write(a)
由此,我得到了警告:

/python3.7/site packages/matplotlib/colors.py:512:RuntimeWarning: 在较小的xa中遇到无效值[xa<0]=-1

而且,如下图所示,
30d
1y
列的渲染不正确,因为它们有NaN列。我如何才能使其忽略NaN,并仅使用有效值渲染颜色?将NaN设置为0是无效的选项,因为这里的NaN本身就有意义


有点晚了,但供以后参考

我也有同样的问题,下面是我如何解决的:

import pandas as pd
import numpy as np
dt = pd.DataFrame({'col1': [1,2,3,4,5], 'col2': [4,5,6,7,np.nan], 'col3': [8,2,6,np.nan,np.nan]})
首先在nas中填入一个较大的值

dt.fillna(dt.max().max()+1, inplace=True)
函数将此最大值的字体颜色设置为白色

def color_max_white(val, max_val):
    color = 'white' if val == max_val else 'black'
    return 'color: %s' % color
def highlight_max(data, color='white'):
    attr = 'background-color: {}'.format(color)
    if data.ndim == 1:  # Series from .apply(axis=0) or axis=1
        is_max = data == data.max()
        return [attr if v else '' for v in is_max]
    else:  # from .apply(axis=None)
        is_max = data == data.max().max()
        return pd.DataFrame(np.where(is_max, attr, ''),
                            index=data.index, columns=data.columns)
函数将最大值的背景颜色设置为白色

def color_max_white(val, max_val):
    color = 'white' if val == max_val else 'black'
    return 'color: %s' % color
def highlight_max(data, color='white'):
    attr = 'background-color: {}'.format(color)
    if data.ndim == 1:  # Series from .apply(axis=0) or axis=1
        is_max = data == data.max()
        return [attr if v else '' for v in is_max]
    else:  # from .apply(axis=None)
        is_max = data == data.max().max()
        return pd.DataFrame(np.where(is_max, attr, ''),
                            index=data.index, columns=data.columns)
把所有的东西放在一起

max_val = dt.max().max()

dt.style.format("{:.2f}").background_gradient(cmap='Blues', axis=None).applymap(lambda x: color_max_white(x, max_val)).apply(highlight_max, axis=None)


帮助我找到答案

@quant的答案几乎对我有用,但我的背景渐变仍然使用最大值来计算颜色渐变。我实现了@night train的建议来设置彩色地图,然后使用了两个功能:

import copy
cmap = copy.copy(plt.cm.get_cmap("Blues"))
cmap.set_under("white")

def color_nan_white(val):
    """Color the nan text white"""
    if np.isnan(val):
        return 'color: white'

def color_nan_white_background(val):
     """Color the nan cell background white"""
    if np.isnan(val):
        return 'background-color: white'
然后将它们应用到我的数据帧中,再次借用@quant,并稍加修改以方便:

(df.style
    .background_gradient(axis='index')
    .applymap(lambda x: color_nan_white(x))
    .applymap(lambda x: color_nan_white_background(x))
)

然后它工作得很好。

您希望如何渲染南部?只有白色背景?@wpercy只有纯白色或蓝色这是因为numpy如何处理NaN值,不确定解决方法是什么,相应的熊猫问题已经解决。您可能会使用一些表示NaN的唯一小值进行填充。您也可以更改颜色映射
cmap=copy.copy(plt.cm.get\u cmap(“蓝色”))
然后在(“白色”)下设置
cmap.set\u
。出于某种原因,熊猫将nan值解释为“低于”而不是“不好”,但无论如何,这只需要很少的努力。