核心内容

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.style Styler
  • 导出带样式的文件:使用 Styler 的 to_html() / to_excel() / to_latex()

相关笔记