核心内容

Styler 对象提供一系列 格式化方法,控制表格的显示格式、隐藏、属性、标题等。

一、format() — 格式化单元格

import pandas as pd
 
df = pd.DataFrame({
    '城市': ['北京', '上海', '广州'],
    '人口': [21893095, 24870895, 18676605],
    'GDP': [41610.9, 44652.8, 28231.9],
    '增长': [0.052, 0.048, 0.041]
})
 
# 1. 全局格式(所有列)
df.style.format('{:.2f}')
 
# 2. 按列指定格式
df.style.format({'人口': '{:,.0f}', 'GDP': '¥{:,.1f} 亿', '增长': '{:.2%}'})
 
# 3. 使用格式字符串语法(Python format spec)
df.style.format({'增长': '{:.2%}'})
 
# 4. 使用函数
df.style.format({'GDP': lambda x: f'{x:,.1f}'})
 
# 5. 设置缺失值显示
df.style.format(na_rep='N/A')
参数说明
formatter格式字符串 / 字典 / 可调用对象
na_rep缺失值显示文本
precision精度(使用默认格式时)
decimal小数分隔符
thousands千分位分隔符

二、format_index() — 格式化索引

df = df.set_index('城市')
 
# 格式化行索引
df.style.format_index('【{}】')
 
# 格式化列索引
df.style.format_index(axis=1, formatter=str.upper)
 
# 格式化多级索引的特定层级
df.style.format_index(level=0, formatter=lambda x: f'→ {x}')

三、hide() / hide_index() — 隐藏行列

# 隐藏行索引
df.style.hide(axis='index')
 
# 隐藏列索引
df.style.hide(axis='columns')
 
# 隐藏特定列(通过 subset)
df.style.hide(['增长'], axis='columns')
 
# 隐藏特定行
df.style.hide([0, 2], axis='index')
 
# 旧版 API(2.x 已弃用,推荐 hide)
df.style.hide_index()
df.style.hide_columns(['增长'])

弃用提示

hide_index() / hide_columns() 在 pandas 2.x 中被 hide(axis=...) 取代,建议使用新 API。

四、set_properties() — 批量设置 CSS 属性

df.style.set_properties(**{
    'text-align': 'center',
    'font-size': '12pt',
    'background-color': '#f0f8ff',
    'border': '1px solid #ccc',
    'width': '100px'
})

五、set_caption() — 设置表格标题

df.style.set_caption('📊 城市经济数据')   # 不要 emoji 也可
# 实际使用:
df.style.set_caption('城市经济数据(2025)')

六、set_table_styles() — 设置表格级样式

df.style.set_table_styles([
    # 表头样式
    {'selector': 'thead tr th',
     'props': [('background-color', '#4a90d9'),
               ('color', 'white'),
               ('font-weight', 'bold')]},
    # 行悬停效果
    {'selector': 'tbody tr:hover',
     'props': [('background-color', '#f5f5f5')]},
    # 表格边框
    {'selector': 'table',
     'props': [('border-collapse', 'collapse'),
               ('width', '100%')]}
])

七、set_table_attributes() — 设置 table 标签属性

# 添加 CSS 类名与自定义属性
df.style.set_table_attributes('class="dataframe table table-striped" id="city_table"')
 
# 用于导出 HTML 后嵌入网页
html = df.style.set_table_attributes('class="my-table"').to_html()

八、set_uuid() — 设置唯一标识

# 默认自动生成 UUID,用于 CSS 隔离
df.style.set_uuid('custom_id')
 
# 多个表格同页展示时可手动指定避免冲突

九、apply() — 应用自定义样式函数

apply() 作用于 行 / 列 / 整个 DataFrame,函数返回样式字符串或样式 DataFrame。

# 1. 按列:每列独立传入;返回样式 Series(index 为行)
def highlight_above_mean(s: pd.Series) -> pd.Series:
    is_max = s == s.max()
    return ['font-weight: bold; color: red' if v else '' for v in is_max]
 
df.style.apply(highlight_above_mean, axis=0)
 
# 2. 按行
df.style.apply(
    lambda row: ['background-color: yellow' if row['销量'] > 100 else '' 
                 for _ in row],
    axis=1
)
 
# 3. 整个 DataFrame
def highlight_outliers(frame: pd.DataFrame) -> pd.DataFrame:
    style = pd.DataFrame('', index=frame.index, columns=frame.columns)
    style[frame > frame.mean() + 2 * frame.std()] = 'color: red'
    return style
 
df.style.apply(highlight_outliers, axis=None)
 
# 4. subset 参数限定范围
df.style.apply(highlight_above_mean, subset=['销量'])
参数说明
func样式函数
axis0(列)/ 1(行)/ None(整个表)
subset限定应用范围(列名或行列选择器)
**kwargs传递给 func 的额外参数

十、map() — 逐元素应用样式

map()(旧名 applymap)对每个单元格调用函数,返回样式字符串。

# 单条件样式
def color_by_value(v):
    if v > 100:
        return 'color: green; font-weight: bold'
    elif v < 50:
        return 'color: orange'
    return ''
 
df.style.map(color_by_value, subset=['销量'])
 
# 同时设置背景与文字颜色
def style_cell(v):
    if pd.isna(v):
        return 'background-color: #f0f0f0; color: gray'
    return 'background-color: rgba(0, 128, 0, 0.1)' if v > 0 else ''
 
df.style.map(style_cell)
 
# 多列不同规则
df.style.map(
    lambda v: 'color: blue' if v > 100 else '',
    subset=['销量']
).map(
    lambda v: 'color: red' if v < 0.05 else '',
    subset=['增长']
)

apply() 与 map() 的区别

  • apply():传入一行 / 一列 / 整个表,适合跨值比较(如最大值、均值)
  • map():传入单个值,适合逐值判断

十一、apply_index() — 索引样式

# 行索引样式
def style_index(idx):
    return ['font-weight: bold' if 'A' in str(v) else '' for v in idx]
 
df.style.apply_index(style_index)
 
# 列索引样式(axis=1)
df.style.apply_index(lambda col: ['color: #337ab7'] * len(col), axis=1)
 
# 多级索引 level 参数
df.style.apply_index(style_index, level=0)

方法速查表

方法作用
format()格式化单元格显示
format_index()格式化索引显示
hide()隐藏行 / 列
hide_index() / hide_columns()旧版隐藏 API
set_properties()批量设置 CSS 属性
set_caption()设置表格标题
set_table_styles()设置 table / th / td 样式
set_table_attributes()设置 <table> 标签属性
set_uuid()设置表格唯一 ID
apply()按行 / 列 / 表应用样式函数
map()逐元素应用样式函数
apply_index()应用索引样式函数

相关笔记