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

如何在Python中为Pandas DataFrame表头添加边框?

给Pandas DataFrame表头添加边框的解决方案

嘿,这个问题我之前也碰到过!你用的set_properties()确实只对表格主体(tbody里的单元格)生效,表头(thead)得单独用set_table_styles()来配置样式才行。给你两个实用的解决方案:

方案一:统一设置表头+主体的边框

这个方法能让整个表格的边框样式保持一致,代码也很简洁:

import pandas as pd

# 示例DataFrame(替换成你自己的即可)
df = pd.DataFrame({'列1': [1, 2, 3], '列2': [4, 5, 6], '列3': [7, 8, 9]})

# 第一步:给表头设置边框
styled_df = df.style.set_table_styles([
    {'selector': 'th',  # 选中所有表头单元格
     'props': [('border', '1px solid black')]}  # 边框样式:1px黑色实线
])

# 第二步:给主体单元格设置你原来想要的样式
styled_df = styled_df.set_properties(**{
    'background-color': 'white',
    'color': 'black',
    'border': '1px solid black'
})

# 在Jupyter里直接运行就能看到效果,导出HTML的话用styled_df.to_html()
styled_df

方案二:自定义差异化样式(更灵活)

如果想让表头和主体的边框有区别(比如表头边框更粗、加个背景色),可以分开写CSS规则:

styled_df = df.style.set_table_styles([
    # 表头专属样式
    {'selector': 'thead th',
     'props': [('border', '2px solid #333'),  # 更粗的深灰色边框
               ('background-color', '#f5f5f5')]},  # 浅灰色背景
    # 主体单元格样式
    {'selector': 'tbody td',
     'props': [('border', '1px solid #666'),  # 细一点的灰色边框
               ('background-color', 'white'),
               ('color', 'black')]}
])

小提示

  • 如果要导出成HTML文件,直接用styled_df.to_html('带边框的表格.html'),样式会完整保留
  • 在Jupyter Notebook里运行代码,就能实时看到带完整边框的表格啦

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:38:08