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

如何使用Pandas将指定列标题设置为斜体?

仅将特定列标题设置为斜体的解决方案

要单独把列标题"b"设为斜体,你可以通过精准的CSS选择器定位到这个特定的表头单元格,替换原来的整行样式设置。以下是修改后的完整代码:

import pandas as pd
col = pd.MultiIndex.from_arrays([["", "one", "one", "two", "two"],
                                 ["a", "b", "c", "d", "e"]])
df = pd.DataFrame(data=[["first", 20, 30, 50, 80],
                        ["second", 30, 40, 90, 20],],
                 columns=col, 
                 )
df_styled = df.style.hide(axis="index")
# 仅选中level1层级中内容为"b"的表头单元格
df_styled.set_table_styles([
    {'selector': 'th.col_heading.level1:contains("b")', 'props': 'font-style: italic;'},
], overwrite=False)

# 导出或显示HTML
print(df_styled.to_html())

补充说明:

  • 如果担心:contains()选择器可能匹配到重复内容,可以通过列的位置精准定位。"b"是level1层级的第2个表头(从1开始计数),对应的选择器为:
    {'selector': 'th.col_heading.level1:nth-child(2)', 'props': 'font-style: italic;'},
    
  • 两种方法都能实现目标,前者更直观(按内容匹配),后者更稳定(按位置匹配),可根据实际场景选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:18:20