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

使用Pandas(Python)实现多行跨列表头及单元格背景色设置

Pandas表格:跨列合并表头与单元格背景色设置

一、跨列合并表头([0,3]至[0,6])

Pandas原生MultiIndex不支持直接合并表头单元格,需借助Styler自定义HTML样式实现。核心逻辑是通过CSS为目标单元格设置colspan属性,并隐藏被合并的单元格。

示例代码:

import pandas as pd
import numpy as np

# 构造多层表头
headers0 = ['',     '',      '',          '7 dies', '...',   '...',    '...']
headers1 = ['',     'Màxim', 'Mitjana',   '',       '',      '',       'Balanç']
headers2 = ['Lloc', 'diari', '(30 dies)', 'Consum', 'Màxim', 'Balanç', '%']
# 构造示例数据
df = pd.DataFrame(
    np.random.randn(5,7),
    columns=pd.MultiIndex.from_arrays([headers0,headers1,headers2])
)

# 定义表头合并样式
def merge_header(styler):
    styler.set_table_styles([
        # 设置第一层表头第4个单元格(对应[0,3])跨4列
        {'selector': 'thead tr:first-child td:nth-child(4)',
         'props': [('colspan', '4'), ('text-align', 'center')]},
        # 隐藏被合并的后续3个单元格
        {'selector': 'thead tr:first-child td:nth-child(5), thead tr:first-child td:nth-child(6), thead tr:first-child td:nth-child(7)',
         'props': [('display', 'none')]}
    ])
    return styler

# 应用样式并导出查看
styled_df = df.style.pipe(merge_header)
styled_df.to_html('merged_table.html')

二、设置单元格背景色

通过Styler的apply/applymap方法实现,可针对表头、数据行或特定单元格自定义样式。

1. 给表头行设置背景色

def style_header_bg(styler):
    styler.set_table_styles([
        {'selector': 'thead th',
         'props': [('background-color', '#f0f0f0'), ('font-weight', 'bold')]}
    ])
    return styler

# 组合表头合并+背景色样式
styled_df = df.style.pipe(merge_header).pipe(style_header_bg)

2. 给特定数据单元格设置背景色

比如给第一行第三列单元格设置背景色:

def highlight_target_cell(styler):
    def apply_style(val):
        # 匹配目标单元格的多层索引
        if val.name == (0, headers0[2], headers1[2], headers2[2]):
            return 'background-color: #ffcccc'
        return ''
    return styler.applymap(apply_style)

# 组合所有样式
styled_df = df.style.pipe(merge_header).pipe(style_header_bg).pipe(highlight_target_cell)

导出Excel格式的样式表格

若需导出带合并表头和背景色的Excel,可使用openpyxl引擎手动设置:

from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment
from openpyxl.utils.dataframe import dataframe_to_rows

wb = Workbook()
ws = wb.active

# 写入表格数据(含表头)
for r_idx, row in enumerate(dataframe_to_rows(df, index=False, header=True), 1):
    ws.append(row)

# 合并表头单元格D1到G1(对应[0,3]至[0,6])
ws.merge_cells('D1:G1')
ws['D1'].alignment = Alignment(horizontal='center')

# 设置表头背景色
fill = PatternFill(start_color='f0f0f0', end_color='f0f0f0', fill_type='solid')
for cell in ws[1]:
    cell.fill = fill

wb.save('styled_table.xlsx')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:50:16