Pandas Style 为数据表格美颜

本文介绍如何使用 Pandas 的 Styler 对 DataFrame 进行样式设置,包括应用样式函数、切片选择、值的格式化等技巧,并展示了如何创建热力图背景、设置单元格属性及导出样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

1. 创建样式

传递样式函数的方法:

  • Styler.applymap: 逐个元素,返回带有CSS属性-值对的单个字符串。

  • Styler.apply: 列/行/表方式,返回形状相同的Series或DataFrame,其中每个值都是带有CSS属性值对的字符串。

Styler.applymap 作用于DataFrame中的每一个元素。Styler.apply 通过axis参数,每一次将一列或一行或整个表传递到DataFrame中。对于按列使用 axis=0, 按行使用 axis=1, 整个表使用 axis=None.


 
  1. import pandas as pd

  2. import numpy as np

  3.  
  4. np.random.seed(24)

  5. df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

  6. df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],

  7.                axis=1)

  8. df.iloc[3, 3] = np.nan

  9. df.iloc[0, 2] = np.nan


 
  1. # 默认无样式

  2. df.style

「注意」DataFrame.style 返回Styler对象的属性。


 
  1. # 通过调用.render方法来查看它们

  2. df.style.highlight_null().render().split('\n')[:10]


 
  1. ['<style  type="text/css" >',

  2.  '    #T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col2 {',

  3.  '            background-color:  red;',

  4.  '        }    #T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow3_col3 {',

  5.  '            background-color:  red;',

  6.  '        }</style><table id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdcc" ><thead>    <tr>        <th class="blank level0" ></th>        <th class="col_heading level0 col0" >A</th>        <th class="col_heading level0 col1" >B</th>        <th class="col_heading level0 col2" >C</th>        <th class="col_heading level0 col3" >D</th>        <th class="col_heading level0 col4" >E</th>    </tr></thead><tbody>',

  7.  '                <tr>',

  8.  '                        <th id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdcclevel0_row0" class="row_heading level0 row0" >0</th>',

  9.  '                        <td id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col0" class="data row0 col0" >1.000000</td>',

  10.  '                        <td id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col1" class="data row0 col1" >1.329212</td>']

编写一个简单的样式函数,该函数会将负数涂成红色,将正数涂成黑色。


 
  1. def color_negative_red(val):

  2.     """

  3.     Takes a scalar and returns a string with

  4.     the css property `'color: red'` for negative

  5.     strings, black otherwise.

  6.     """

  7.     color = 'red' if val < 0 else 'black'

  8.     return 'color: %s' % color

在这种情况下,单元格的样式仅取决于其自身的值。我们应该使用在 Styler.applymap作用于每个元素。

df.style.applymap(color_negative_red)

定义一个突出显示每列中的最大值的函数。


 
  1. def highlight_max(s):

  2.     '''

  3.     highlight the maximum in a Series yellow.

  4.     '''

  5.     is_max = s == s.max()

  6.     return ['background-color: yellow' if v else '' for v in is_max]

df.style.apply(highlight_max)

实际上,已有定义好的各类高亮函数:

配合axis参数使用

  • highlight_max():高亮最大值

  • highlight_min():高亮最小值

  • highlight_null():高亮空值


 
  1. # 高亮行最大值

  2. df.style.highlight_max(axis=1)

使用链式操作进行定义样式

df.style.applymap(color_negative_red).apply(highlight_max)

2. 切片

subset 参数控制作用的行列。

subset 传入的参数类似DataFrame的切片:

  • 列标签

  • 列表(或者numpy数组)

  • 元组(row_indexer, column_indexer)

df.style.apply(highlight_max, subset=['B', 'C', 'D'])

使用pd.IndexSlice构造一个切片元组。


 
  1. # B, D两列,2:5行中的负数标红 

  2. df.style.applymap(color_negative_red,

  3.                   subset=pd.IndexSlice[2:5, ['B', 'D']])

「注意」:目前仅支持基于标签的切片,不支持位置切片。

3.值的显示格式

使用Styler.format控制。类似字符串输出方法。

df.style.format("{:.2%}")

使用字典来格式化特定的列。

df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})

使用lambda函数。

df.style.format({"B": lambda x: "±{:.2f}".format(abs(x))})

使用 na_rep设置空值的显示。

df.style.format("{:.2%}", na_rep="空值")

df.style.highlight_max().format(None, na_rep="-")

4. 内置样式函数

参考链接:https://pandas.pydata.org/docs/reference/style.html


 
  1. # 高亮空值

  2. df.style.highlight_null(null_color='red')

使用background_gradient 创建“热力图”式背景。需要配合matplotlib或者Seaborn使用。


 
  1. import seaborn as sns

  2. cm = sns.light_palette("green", as_cmap=True)

  3.  
  4. df.style.background_gradient(cmap=cm)


 
  1. # Uses the full color range

  2. df.loc[:4].style.background_gradient(cmap='viridis')

使用关键字参数lowhigh限定色谱百分比范围。


 
  1. # Compress the color range

  2. (df.loc[:4]

  3.     .style

  4.     .background_gradient(cmap='viridis', low=.5, high=0)

  5.     .highlight_null('red'))

当样式不取决于值时,使用set_properties 。


 
  1. df.style.set_properties(**{'background-color': 'black',

  2.                            'color': 'lawngreen',

  3.                            'border-color': 'white'})

5. 数据中包含“条形图”

df.style.bar(subset=['A', 'B'], color='#d65f5f')

使用align 控制对其方式:

  • left: 最小值从单元格的左侧开始。

  • zero: 零值位于单元格的中心。

  • mid: t单元格的中心在(max-min)/ 2,或者如果值全为负(正),则零对齐于单元格的右(左)。

df.style.bar(subset=['A', 'B'], align='mid', color=['#d65f5f', '#5fba7d'])

6. 共享样式

假设为DataFrame建立了一个样式,想将相同样式应用于第二个DataFrame。使用df1.style.export导出样式。


 
  1. df2 = -df

  2. style1 = df.style.applymap(color_negative_red)

  3. style1


 
  1. style2 = df2.style

  2. style2.use(style1.export())

  3. style2

7. 其他样式

精度set_precision

df.style.applymap(color_negative_red).apply(highlight_max).set_precision(2)

标题set_caption


 
  1. df.style.set_caption('Colormaps, with a caption.')\

  2.     .background_gradient(cmap=cm)

表格整体样式set_table_styles


 
  1. from IPython.display import HTML

  2.  
  3. def hover(hover_color="#ffff99"):

  4.     return dict(selector="tr:hover",

  5.                 props=[("background-color", "%s" % hover_color)])

  6.  
  7. styles = [

  8.     hover(),

  9.     dict(selector="th", props=[("font-size", "150%"),

  10.                                ("text-align", "center")]),

  11.     dict(selector="caption", props=[("caption-side", "top")])

  12. ]

  13. html = (df.style.set_table_styles(styles)

  14.           .set_caption("Hover to highlight."))

  15. html

缺失值set_na_rep


 
  1. (df.style

  2.    .set_na_rep("FAIL")

  3.    .format(None, na_rep="PASS", subset=["D"])

  4.    .highlight_null("yellow"))

隐藏索引hide_index或列hide_columns


 
  1. # 隐藏索引

  2. df.style.hide_index()


 
  1. #隐藏列

  2. df.style.hide_columns(['C','D'])

8. 导出为Excel(还在开发实验阶段)

DataFrames 使用「OpenPyXL」「XlsxWriter」引擎可以将样式导出到Excel工作表。CSS2.2处理的属性包括:

  • background-color

  • border-styleborder-widthborder-color and their {toprightbottomleft variants}

  • color

  • font-family

  • font-style

  • font-weight

  • text-align

  • text-decoration

  • vertical-align

  • white-space: nowrap

  • 当前仅支持CSS2命名或十六进制颜色,格式为 #rgb#rrggbb


 
  1. df.style.\

  2.     applymap(color_negative_red).\

  3.     apply(highlight_max).\

  4.     to_excel('styled.xlsx', engine='openpyxl')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值