熊猫 style.background_gradient 忽略 NaN

我有以下代码将数据帧转储results到 HTML 表格中,以便TIME_FRAMES根据 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: 在less xa[xa < 0] = -1 中遇到无效值


而且,正如您在下图中所看到的,列30d和1y无法正确呈现,因为它们具有 NaN。我怎样才能做到这一点,以便忽略 NaN 并且仅使用有效值呈现颜色?将 NaN 设置为 0 不是一个有效的选项,因为这里的 NaN 本身就具有意义。

http://img4.mukewang.com/61d500880001337a04000563.jpg

茅侃侃
浏览 385回答 3
3回答

杨__羊羊

有点晚了,但供以后参考。我遇到了同样的问题,这是我解决的方法:import pandas as pdimport numpy as npdt = pd.DataFrame({'col1': [1,2,3,4,5], 'col2': [4,5,6,7,np.nan], 'col3': [8,2,6,np.nan,np.nan]})先填入一个大值的nasdt.fillna(dt.max().max()+1, inplace=True)将此最大值的字体着色为白色的函数def color_max_white(val, max_val):&nbsp; &nbsp; color = 'white' if val == max_val else 'black'&nbsp; &nbsp; return 'color: %s' % color将最大值的背景着色为白色的函数def highlight_max(data, color='white'):&nbsp; &nbsp; attr = 'background-color: {}'.format(color)&nbsp; &nbsp; if data.ndim == 1:&nbsp; # Series from .apply(axis=0) or axis=1&nbsp; &nbsp; &nbsp; &nbsp; is_max = data == data.max()&nbsp; &nbsp; &nbsp; &nbsp; return [attr if v else '' for v in is_max]&nbsp; &nbsp; else:&nbsp; # from .apply(axis=None)&nbsp; &nbsp; &nbsp; &nbsp; is_max = data == data.max().max()&nbsp; &nbsp; &nbsp; &nbsp; return pd.DataFrame(np.where(is_max, attr, ''),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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)

小怪兽爱吃肉

这对我来说很好用df.style.applymap(lambda&nbsp;x:&nbsp;'color:&nbsp;transparent'&nbsp;if&nbsp;pd.isnull(x)&nbsp;else&nbsp;'')

慕勒3428872

我的背景渐变仍会使用最大值来计算颜色渐变。我实现了@night-train 的设置颜色图的建议,然后使用了两个函数:import copycmap = copy.copy(plt.cm.get_cmap("Blues"))cmap.set_under("white")def color_nan_white(val):&nbsp; &nbsp; """Color the nan text white"""&nbsp; &nbsp; if np.isnan(val):&nbsp; &nbsp; &nbsp; &nbsp; return 'color: white'def color_nan_white_background(val):&nbsp; &nbsp; &nbsp;"""Color the nan cell background white"""&nbsp; &nbsp; if np.isnan(val):&nbsp; &nbsp; &nbsp; &nbsp; return 'background-color: white'然后再次将它们应用到我的数据帧中,为方便起见,从@quant 中借用了一点:(df.style&nbsp; &nbsp; .background_gradient(axis='index')&nbsp; &nbsp; .applymap(lambda x: color_nan_white(x))&nbsp; &nbsp; .applymap(lambda x: color_nan_white_background(x)))然后它完美地工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python