核心内容
pandas 的「表格样式」既包括全局显示层面的样式控制,也包括
DataFrame.style的 Styler 对象实现的精细化样式。
一、全局显示样式
通过 display 选项影响控制台表格样式:
| 选项 | 效果 |
|---|---|
display.colheader_justify | 列标题对齐 |
display.expand_frame_repr | 是否换行展开 |
display.show_dimensions | 是否显示维度 |
display.unicode.east_asian_width | 东亚字符宽度对齐 |
import pandas as pd
pd.set_option('display.colheader_justify', 'center')
pd.set_option('display.unicode.east_asian_width', True) # 中文对齐更美观二、Styler 对象
DataFrame.style 返回 Styler 对象,支持链式调用:
df.style.highlight_max().format('{:.2f}')常用属性
styler = df.style
styler.data # 原始数据
styler.index # 行索引
styler.columns # 列索引
styler.hide(axis='index') # 隐藏索引链式调用示例
df.style \
.format('{:.2f}') \
.highlight_max(color='lightgreen') \
.set_properties(**{'text-align': 'center'})三、样式作用层级
样式函数(highlight_* 等) > 格式化方法(format 等) > 全局显示选项(display.*)
选用建议
- 控制台输出:使用
display.*选项- Jupyter / HTML 展示:使用
DataFrame.styleStyler- 导出带样式的文件:使用 Styler 的
to_html()/to_excel()/to_latex()
相关笔记
- Pandas-二十二-样式与格式化-MOC - Styler 完整指南
- 20.4 显示格式化 - 控制台显示选项
- 20.2 浮点格式 - 浮点数字格式