You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn热力图Format strings FutureWarning无法消除问题求助

解决Seaborn热力图的MaskedConstant格式警告问题

问题重现

现有如下DataFrame:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'Item': [19, 92],
        '16': [None, 1],
        '56': [1, None],
        '70': [1, None]}

df = pd.DataFrame(data).set_index('Item')

使用Seaborn绘制热力图的代码:

fig, ax = plt.subplots(figsize=(20,10))
sns.heatmap(df, cmap="Reds", annot=True, cbar=False, linewidth=1, ax=ax)
plt.show()

环境更新后出现以下警告:

FutureWarning: Format strings passed to MaskedConstant are ignored,
but in future may error or produce different behavior
annotation =
("{:" + self.fmt + "}").format(val)

尝试传入fmt='.2g'或定义mask = df.isnull()均无法消除警告。

解决方案

方法1:预处理DataFrame,替换NaN为空字符串

将DataFrame中的NaN值替换为空字符串,然后将处理后的表格传入annot参数,同时设置fmt=''跳过格式化:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'Item': [19, 92],
        '16': [None, 1],
        '56': [1, None],
        '70': [1, None]}

df = pd.DataFrame(data).set_index('Item')
# 替换NaN为空字符串,用于标注显示
df_annot = df.fillna('')

fig, ax = plt.subplots(figsize=(20,10))
# 传入处理后的标注数据,设置fmt=''避免格式化空值
sns.heatmap(df, cmap="Reds", annot=df_annot, cbar=False, linewidth=1, ax=ax, fmt='')
plt.show()

方法2:自定义标注函数

通过annot_kws传入自定义函数,手动判断并处理每个值的标注内容,跳过NaN值:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'Item': [19, 92],
        '16': [None, 1],
        '56': [1, None],
        '70': [1, None]}

df = pd.DataFrame(data).set_index('Item')

def annotate_val(val):
    # 对非NaN值格式化,NaN值返回空字符串
    if pd.notna(val):
        return f'{val:.2g}'
    return ''

fig, ax = plt.subplots(figsize=(20,10))
sns.heatmap(df, cmap="Reds", annot=True, cbar=False, linewidth=1, ax=ax, 
            fmt='', annot_kws={'func': annotate_val})
plt.show()

问题原因

之前的尝试无效是因为:

  • 使用mask=df.isnull()仅隐藏了热力图的色块,但annot=True仍会尝试对被掩码的NaN(内部以MaskedConstant类型存在)应用格式化规则,触发警告。
  • 直接传入fmt参数时,Seaborn内部仍会对MaskedConstant执行格式化操作,导致警告出现。

内容的提问来源于stack exchange,提问作者heartbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 11:17:25