python - Pandas style.background_gradient 忽略 NaN

标签 python pandas seaborn

我有以下代码来转储数据帧 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: invalid value encountered in less xa[xa < 0] = -1



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

enter image description here

最佳答案

有点晚,但供以后引用。
我遇到了同样的问题,这是我解决的方法:

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)
把所有东西放在一起
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)
enter image description here
This link帮我解答

关于python - Pandas style.background_gradient 忽略 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55596049/

相关文章:

python - super() 为新式类引发 "TypeError: must be type, not classobj"

python - 如何在 USB 闪存中创建 Python 虚拟环境

python - Pandas 迭代行并从另一列中删除一列中的字符串值

python - seaborn 与 pandas 中的 y 轴缩放

python - Google App Engine - 从 Aptana Studio 运行 python shell 命令时出现问题

python - 过滤 pandas DataFrame 中的行

python - 尝试在 DataFrame.pivot 中使用多索引时出现 ValueError

python - 在条形图中使用色调时,让 seaborn 显示颜色条而不是图例?

pandas - lmplot seaborn 中每种色调的不同标记

Python 日志记录模块 - 从命令行运行时输出到文本文件