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

使用PdfPages导出PDF时,如何高亮DataFrame中的NaN值?

解决方案:高亮DataFrame的NaN值并导出到PDF

你之前的问题核心在于:df.style.highlight_null('red')仅生成了样式对象,但未将样式关联到手动创建的ax.table;而seaborn heatmap是独立的热力图元素,无法和你添加的表格合并为带高亮的完整表格。以下是两种可行的实现方式:

方法一:手动遍历单元格设置NaN背景色

直接操作matplotlib表格对象,逐个检查单元格值并为NaN设置红色背景:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

# 替换为你的目标DataFrame
df = pd.DataFrame({
    '列1': [1, np.nan, 3],
    '列2': [np.nan, 5, 6],
    '列3': [7, 8, np.nan]
})

with PdfPages('stale_curve_report.pdf') as pdf:
    fig, ax = plt.subplots(figsize=(12, 5))
    ax.axis('off')
    
    # 创建基础表格
    table = ax.table(
        cellText=df.values,
        colLabels=df.columns,
        rowLabels=df.index,
        loc='center',
        colWidths=[0.12] * len(df.columns)
    )
    
    # 遍历数据单元格,为NaN设置红色背景
    for row_idx in range(len(df.index)):
        for col_idx in range(len(df.columns)):
            if pd.isna(df.iloc[row_idx, col_idx]):
                # 表格行索引规则:0为列标题行,数据行从1开始;列索引对应DataFrame的列顺序
                cell = table.get_celld()[(row_idx + 1, col_idx)]
                cell.set_facecolor('red')
    
    pdf.savefig(fig, bbox_inches='tight')
    plt.close(fig)

方法二:利用Pandas Styler渲染带样式的表格

直接借助Pandas内置的样式功能生成带高亮的表格,再嵌入到PDF中:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

df = pd.DataFrame({
    '列1': [1, np.nan, 3],
    '列2': [np.nan, 5, 6],
    '列3': [7, 8, np.nan]
})

# 生成带NaN红色高亮的样式对象,可额外添加表格边框增强可读性
styled_df = df.style.highlight_null('red').set_table_styles([
    {'selector': 'table', 'props': [('border', '1px solid #ccc')]}
])

with PdfPages('stale_curve_report.pdf') as pdf:
    fig, ax = plt.subplots(figsize=(12, 5))
    ax.axis('off')
    # 将样式表格渲染为HTML并导入到matplotlib轴
    from matplotlib.table import table_from_string
    table = table_from_string(ax, styled_df.render(), loc='center')
    
    pdf.savefig(fig, bbox_inches='tight')
    plt.close(fig)

选择建议

  • 方法一兼容性更强,适合需要自定义复杂表格布局的场景;
  • 方法二代码更简洁,依赖Pandas原生样式能力,适合快速实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:37:44