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

如何为pandas的DataFrame添加自定义标题 以一月日历表格为例

解决方案

直接调用pandas Styler内置的set_caption()方法即可为表格添加标题,你原有代码仅需在链式调用最后追加该方法即可,修改后的完整代码如下:

import pandas as pd
January= [['','','','','',1 ,2],[t for t in range(3,10)],[t for t in range(10,17)],[t for t in range(17,24)],
         [t for t in range(24,31)],[31,'','','','','','']]

df = pd.DataFrame(January, columns=['Mo','Di','Mi','Do','Fr','Sa','So'])
df.style.hide_index()\
    .set_table_styles([
        {'selector' : '','props' : [('border','1px solid black')]},
        # 可选:添加标题的样式配置,不需要可以删掉这段
        {'selector': 'caption', 'props': [
            ('font-weight', 'bold'),
            ('font-size', '18px'),
            ('margin-bottom', '6px'),
            ('text-align', 'center')
        ]}
    ])\
    .set_caption("January")

如果不需要调整标题的默认样式,直接追加.set_caption("January")即可,不需要额外修改表格样式配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:09:01