当前pandas版本为:1.2.5。
概述
Jupyter Notebook能够风靡Python数据科学圈的重要原因之一就是可以便捷的显示pandas数据结构。
pandas数据结构在Jupyter Notebook中以表格形式呈现。这些表格的格式化依赖于pandas中的Styler对象。Dateframe.style属性返回值为Styler对象。
Styler对象通过生成CSS样式进行格式化。
Styler类定义在pandas/io/formats/style.py中,具体原理随后详述。
接口概述
格式化主要通过以下方法实现。
Styler.applymap:作用于元素Styler.apply:作用于行、列或整个表
上述方法的调用签名为:
Styler.applymap(func):用于dataframe元素Styler.apply(func, axis=0):用于按列设置样式Styler.apply(func, axis=1):用于按行设置样式Styler.apply(func, axis=None):用于按表格设置样式
以上方法中的func参数即样式回调函数的具体要求如下:
- 回调函数的返回值类型为字符串,格式为CSS属性,即
attribute: value。 - 回调函数的参数与返回值的形状(shape)要一致,即
func(x).shape == x.shape。
由于Styler.applymap和Styler.apply的返回值均为Styler对象,因此,pandas设计了样式的链式调用,即类似Styler.apply.apply的调用方式,这时样式相互叠加。
Styler.applymap和Styler.apply都可以接收subset参数,用于指定样式作用的范围,相当于对DataFrame进行切片操作。该参数有三种取值形式:
- 标量(整数、字符串):列标签
- 列表、系列(series)或numpy array
- 元组:(行索引, 列索引)
Styler对象具有_repr_html_方法,因此在notebook环境中会自动渲染。
Styler对象的render() 方法可返回HTML字符串。
案例基础
import pandas as pd
import matplotlib.pyplot as plt
score = pd.read_csv('./student_score.csv',encoding = 'gbk')
score

接口应用案例
案例1:Styler.applymap(func)演示(按元素格式化)
回调函数的参数为单一的元素,返回值为CSS属性字符串。作用范围为DataFrame中的所有元素。
案例中DataFrame中所有值大于80的元素显示为红色。
def color_red_item(s):
return 'color : red' if s>80 else ''
score.style.applymap(color_red_item)

案例2:Styler.apply(func, axis=0)演示(按列格式化)
回调函数的参数为DataFrame中的列(Series),返回值为CSS属性字符串列表。作用范围为DataFrame中的所有列。
案例中每列最大值显示为红色。
def color_red(s):
return ['color : red' if v==s.max() else '' for v in s]
score.style.apply(color_red])

案例3:Styler.apply(func, axis=1)演示(按行格式化)
回调函数的参数为DataFrame中的行,返回值为CSS属性字符串列表。作用范围为DataFrame中的所有行。
案例中每行最大值显示为红色。
def color_red(s):
return ['color : red' if v==s.max() else '' for v in s]
score.style.apply(color_red,axis=1)

案例4:Styler.apply(func, axis=None)演示(按DataFrame格式化)
回调函数的参数的类型为DataFrame,返回值类型仍然为DataFrame,元素值为CSS属性字符串。
注意!要求参数和返回值的结构和行列索引必须完全一致!
案例中值大于80的元素显示为红色。
import numpy as np
def color_red(s):
return pd.DataFrame(np.where(s>80,'color : red',''),index=s.index, columns=s.columns )
score.style.apply(color_red,axis=None)

案例:回调函数多参数演示
回调函数支持多个参数,除第一个固定参数之外,其余参数在apply或applymap方法中作为关键字参数传入。
def color_red(s,threshold):
items = s > threshold
return ['color : red' if v else '' for v in items]
score.style.apply(color_red,threshold=90)

案例:多个样式链式调用演示
pandas支持链式调用多个样式,样式效果叠加。
def color_red(s):
return ['color : red' if v==s.max() else '' for v in s]
def highlight(s):
return 'background : yellow' if s>80 else ''
score.style.apply(color_red).applymap(highlight)

案例:演示subset参数
subset参数可显示样式设置的范围。
案例仅在高数和英语两列应用样式。
def color_red(s):
return ['color : red' if v==s.max() else '' for v in s]
score.style.apply(color_red, subset=['高数','英语'])


菜鸟笔记