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

Pandas格式化DataFrame高亮列标题及groupby后扁平化多级列头方法

你遇到的列标题不在同一行,不是因为列是多层索引,而是groupby操作默认会将分组键(也就是你指定的TRADEABLE_INSTR_NAME、SIG_CURRENCY_CODE两列)转换为行索引,索引的展示层级低于普通列标题,所以才会出现高低错位的情况,因此你之前搜索的「拍平多层列索引」的方案不适用。

让所有列标题同行

两种方案二选一即可:

  • 方案1:在groupby步骤添加as_index=False参数,让分组键保留为普通列,不会转为索引
    修改后的完整代码如下:
# 新增as_index=False参数
product_splits = dma_fees.groupby(['TRADEABLE_INSTR_NAME','SIG_CURRENCY_CODE'], as_index=False).sum()
product_splits = product_splits.drop('NUMBER_OF_LOTS',axis=1)
product_splits = product_splits.sort_values(by=['DMA_FEE_SUBTOTAL'],ascending=False)
product_splits = product_splits.round({'DMA_FEE_SUBTOTAL': 0}).astype(int)
  • 方案2:如果已经完成了groupby操作,直接调用reset_index()方法将索引转为普通列即可,在现有代码末尾加一行:
product_splits = product_splits.reset_index()

额外需求实现

清除空值

根据你的需求选择对应方案:

  • 直接删除包含空值的行:
product_splits = product_splits.dropna()
  • 自定义填充空值(比如数值列空值填0,文本列空值填空字符串):
product_splits = product_splits.fillna({'TRADEABLE_INSTR_NAME': '', 'SIG_CURRENCY_CODE': '', 'DMA_FEE_SUBTOTAL': 0})

列标题高亮

如果是在Jupyter系列环境中展示,可使用pandas的Styler接口实现:

# 示例为浅黄色背景+加粗的高亮效果,可自行修改background-color的颜色值调整样式
product_splits.style.set_table_styles([
    {'selector': 'th.col_heading', 'props': [('background-color', '#fff2cc'), ('font-weight', 'bold')]}
])

如果需要导出到Excel文件时保留高亮效果,可配合openpyxl实现:

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

wb = Workbook()
ws = wb.active
# 写入DataFrame内容
for r in dataframe_to_rows(product_splits, index=False, header=True):
    ws.append(r)
# 设置第一行(表头)高亮
header_fill = PatternFill(start_color='fff2cc', end_color='fff2cc', fill_type='solid')
header_font = Font(bold=True)
for cell in ws[1]:
    cell.fill = header_fill
    cell.font = header_font
# 保存文件
wb.save('product_splits.xlsx')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:06:03