Pandas Style 为数据表格美颜

Pandas Style 为数据表格美颜来源 牵引小哥讲 Python 作者 牵引小哥 1 创建样式 传递样式函数的方法 Styler applymap 逐个元素 返回带有 CSS 属性 值对的单个字符串 Styler apply 列 行 表方式 返回形状相同的 Series 或 DataFrame 其中每个值都是带有 CSS 属性值对的字符串

大家好,我是讯享网,很高兴认识大家。


讯享网


作者 | 牵引小哥


1. 创建样式

传递样式函数的方法:

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

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

import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],                axis=1) df.iloc[3, 3] = np.nan df.iloc[0, 2] = np.nan 

讯享网
讯享网# 默认无样式 df.style 

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

# 通过调用.render方法来查看它们 df.style.highlight_null().render().split('\n')[:10] 
讯享网['<style  type="text/css" >',  '    #T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col2 {',  '            background-color:  red;',  '        }    #T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow3_col3 {',  '            background-color:  red;',  '        }</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>',  '                <tr>',  '                        <th id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdcclevel0_row0" class="row_heading level0 row0" >0</th>',  '                        <td id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col0" class="data row0 col0" >1.000000</td>',  '                        <td id="T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col1" class="data row0 col1" >1.</td>'] 

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

def color_negative_red(val):     """     Takes a scalar and returns a string with     the css property `'color: red'` for negative     strings, black otherwise.     """     color = 'red' if val < 0 else 'black'     return 'color: %s' % color 

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

讯享网df.style.applymap(color_negative_red) 

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

def highlight_max(s):     '''     highlight the maximum in a Series yellow.     '''     is_max = s == s.max()     return ['background-color: yellow' if v else '' for v in is_max] 
讯享网df.style.apply(highlight_max) 
实际上,已有定义好的各类高亮函数:

配合axis参数使用

  • highlight_max():高亮最大值
  • highlight_min():高亮最小值
  • highlight_null():高亮空值
# 高亮行最大值 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构造一个切片元组。
讯享网# B, D两列,2:5行中的负数标红  df.style.applymap(color_negative_red,                   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

讯享网# 高亮空值 df.style.highlight_null(null_color='red') 
使用background_gradient 创建“热力图”式背景。需要配合matplotlib或者Seaborn使用。
import seaborn as sns cm = sns.light_palette("green", as_cmap=True) df.style.background_gradient(cmap=cm) 
讯享网# Uses the full color range df.loc[:4].style.background_gradient(cmap='viridis') 
使用关键字参数low和high限定色谱百分比范围。
# Compress the color range (df.loc[:4]     .style     .background_gradient(cmap='viridis', low=.5, high=0)     .highlight_null('red')) 
当样式不取决于值时,使用set_properties 。
讯享网df.style.set_properties({'background-color': 'black',                            'color': 'lawngreen',                            '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导出样式。

df2 = -df style1 = df.style.applymap(color_negative_red) style1 
讯享网style2 = df2.style style2.use(style1.export()) style2 

7. 其他样式

精度set_precision

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

标题set_caption

讯享网df.style.set_caption('Colormaps, with a caption.')\     .background_gradient(cmap=cm) 

表格整体样式set_table_styles

from IPython.display import HTML

def hover(hover_color="#ffff99"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])

styles = [
    hover(),
    dict(selector="th", props=[("font-size", "150%"),
                               ("text-align", "center")]),
    dict(selector="caption", props=[("caption-side", "top")])
]
html = (df.style.set_table_styles(styles)
          .set_caption("Hover to highlight."))
html

缺失值set_na_rep

讯享网(df.style    .set_na_rep("FAIL")    .format(None, na_rep="PASS", subset=["D"])    .highlight_null("yellow")) 

隐藏索引hide_index或列hide_columns

# 隐藏索引 df.style.hide_index() 
讯享网#隐藏列 df.style.hide_columns(['C','D']) 

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

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

  • background-color
  • border-style, border-width, border-color and their { top, right, bottom, left variants}
  • color
  • font-family
  • font-style
  • font-weight
  • text-align
  • text-decoration
  • vertical-align
  • white-space: nowrap
  • 当前仅支持CSS2命名或十六进制颜色,格式为 #rgb或#rrggbb。
df.style.\     applymap(color_negative_red).\     apply(highlight_max).\     to_excel('styled.xlsx', engine='openpyxl') 

以上内容参考自:https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

讯享网近期推荐阅读: 【1】整理了我开始分享学习笔记到现在超过250篇优质文章,涵盖数据分析、爬虫、机器学习等方面,别再说不知道该从哪开始,实战哪里找了【2】【终篇】Pandas中文官方文档:基础用法6(含1-5) 如果你觉得文章不错的话,分享、收藏、在看、留言666是对老表的最大支持。 
小讯
上一篇 2025-04-09 22:56
下一篇 2025-02-18 11:16

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/133518.html