参考书目:《深入浅出Pandas:利用Python进行数据处理与分析》
pandas里面的数据框也可以像excel那样做条件样式,并且给予一定的可视化能力,比如找出每行或者每列的最大值标红,低于平均值的数据标黑等等......对于数据科学家使用jupyternotebook处理数据是很方便可视化的。下面一起学习一下这些样式的实现。
还是先导入包和读取案例数据
- import numpy as np
- import pandas as pd
- data = 'https://www.gairuo.com/file/data/dataset/team.xlsx'
- df = pd.read_excel(data)
pandas里面的样式靠df.style这个类实现,首先我们看看他的类型
type(df.style)
![]()
下面我们会用这个类的方法去实现df数据框的样式调整。
#对为空的值,高亮标示。
- df.iloc[1,1] = np.NaN # 修改一个值空
- df.head().style.highlight_null() # 默认红色

#可以指定颜色:
- # 使用颜色名
- df.head().style.highlight_null(null_color='blue')
- # 使用颜色值
- df.head().style.highlight_null(null_color='#ccc')

- # 最大值高亮,默认黄色
- df.head().style.highlight_max()
- # 最小值高亮
- df.head().style.highlight_min() #每一列的最大最小值

# 同时使用+指定颜色
- (df.head()
- .style.highlight_max(color='lime') # 最大值高亮
- .highlight_min(color='blue') # 最小值
- )

# 指定行上最大最小
- (df.head()
- .style.highlight_max(color='wheat', axis=1) # 最大值高亮, 粉红
- .highlight_min(axis=1,color='lightsteelblue') # 最小值,浅蓝
- )

#也可以作用于指定行:
- # 只对 Q1 起作用
- df.style.highlight_min(subset=['Q1'])
- df.style.highlight_min(subset=['Q1', 'Q2']) # 两列
-
- # 按行,只在这两列进行
- df.head(10).style.highlight_min(axis=1, subset=['Q1','Q2'])

#对指定区间的值进行高亮标注显示,可以是数字,也可以是时间(1.3.0 版本+):
- # Q4 列的 60 到 100 高亮
- df.style.highlight_between(left=60, right=100, subset=['Q4'])
- # axis=None 并将 left 参数作为与输入数据帧匹配的数组提供,常量 right
- df.style.highlight_between(left=[[2,2,3],[2,2,3],[3,3,3]], right=3.5,axis=None, color="#fffd75")
- # 指定 css 样式
- df.style.highlight_between(left=1.5, right=3.5,props='font-weight:bold;color:#e83e8c')
#使用样式高亮显示分位数定义的值(1.3.0 版本+),就是说把指定分位区间的数据高亮。使用 axis=None 对所有集合数据应用分位数。
- df = pd.DataFrame(np.arange(10).reshape(2,5) + 1)
- # 将后四分位的数据高亮,即后 3/4 的数据
- df.style.highlight_quantile(axis=None, q_left=0.25, color="#fffd75")
- # 按行或按列高亮显示分位数,在本例中按行高亮显示
- df.style.highlight_quantile(axis=1, q_left=0.8, color="#fffd75")
- # 使用 props 而不是默认的背景颜色
- df.style.highlight_quantile(axis=None, q_left=0.2, q_right=0.8,props='font-weight:bold;color:#e83e8c')
以渐变样式为文本着色。文本颜色根据每列、每行或每帧中的数据或给定的渐变图谱确定。依赖 matplotlib。
语法是:Styler.text_gradient(cmap='PuBu', low=0, high=0,axis=0, subset=None, vmin=None, vmax=None, gmap=None) 示例如下:
- # 数据集
- df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
- data=[["Stockholm", 21.6, 5.0, 3.2],
- ["Oslo", 22.4, 13.3, 3.1],
- ["Copenhagen", 24.5, 0.0, 6.7]])
- # 按列着色显示值,axis=0,预选数值列
- df.style.text_gradient(axis=0)
- # 使用 axis=None 对所有值进行整体着色
- df.style.text_gradient(axis=None)
- # 从低值和高值颜色着色
- df.style.text_gradient(axis=None, low=0.75, high=1.0)
- # 手动设置vmin和vmax梯度阈值
- df.style.text_gradient(axis=None, vmin=6.7, vmax=21.6)
- # 设置 gmap 并使用另一个 cmap 应用于所有列
- df.style.text_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')
- # 设置数据帧的渐变贴图(即axis=None),我们需要
- # 显式地声明子集以匹配 gmap 形状
- gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
- df.style.text_gradient(axis=None, gmap=gmap,
- cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)'] )
#根据数值的大小背景颜色呈现梯度渐变,越深表示越大,越浅表示越小,类似于 Excel 的中的色阶样式。
- # 数字类型按列背景渐变
- df.style.background_gradient()
- # 指定列,指定颜色系列
- df.style.background_gradient(subset=['Q1'], cmap='BuGn')
- # 低百分比和高百分比范围, 更换颜色时避免使用所有色域
- df.style.background_gradient(low=0.6, high=0)
- # 内容的颜色,取 0-1(深色到浅色),方便突显出文本
- df.style.background_gradient(text_color_threshold=0.5)
- # 颜色应用的取值范围,不在这个范围的不应用
- df.head().style.background_gradient(vmin=60, vmax=90)

#以下是一个综合使用示例:
- # 链式方法使用样式
- (df.head(10)
- .style
- .background_gradient(subset=['Q1'], cmap='spring') # 指定色系
- .background_gradient(subset=['Q2'], vmin=60, vmax=100) # 指定应用值区间
- .background_gradient(subset=['Q3'], low=0.6, high=0) # 高低百分比范围
- .background_gradient(subset=['Q4'], text_color_threshold=0.9) # 文本色深
- )

#条形图在表格里一般以横向柱状图的形式代表这个值的大小。
- # 基本使用,默认将数字应用
- df.head(10).style.bar()

其他参数
- # 指定应用范围
- df.style.bar(subset=['Q1'])
- # 定义颜色
- df.style.bar(color='green')
- df.style.bar(color='#ff11bb')
- # 以向进行计算展示
- df.style.bar(axis=1)
- # 样式在格中的占位百分比,0-100, 100占满
- df.style.bar(width=80)
- # 对齐方式:
- # ‘left’ 最小值开始,
- # ‘zero’ 0值在中间,
- # ’mid’ (max-min)/2 值在中间,负(正)值0在右(左)
- df.style.bar(align='mid')
- # 大小基准值
- df.style.bar(vmin=60, vmax=100)
#以下是一个综合示例:
- (df.head(10)
- .assign(avg=df.mean(axis=1, numeric_only=True)) # 增加平均值
- .assign(diff=lambda x: x.avg.diff()) # 和前位同学差值
- .style
- .bar(color='yellow', subset=['Q1'])
- .bar(subset=['avg'],
- width=90,
- align='mid',
- vmin=60, vmax=100,
- color='#5CADAD')
- .bar(subset=['diff'],
- color=['#bbf9ce','#ffe4e4',], # 上涨下降的颜色
- vmin=0, vmax=30, # 范围定以0为基准的上下30
- align='zero') # 0 值居中
- )

我们在最终输出数据查看时,需要对数据进行相应的格式化,常见的如加货币符号、加百分号、增加千分位等,目的是让计数更加场景化,明确列表一定的业务意义。
Styler.format 是专门用来处理格式的方法。
语法结构 Styler.format(self, formatter,subset=None, na_rep: Union[str,NoneType]=None)
df.head().style.format("[{}]") #给所有数据加上[]

#用法
- # 百分号,类似 29.57%
- df.style.format("{:.2%}")
- # 指定列全变为大写
- df.style.format({'name': str.upper})
- # B 保留四位,D 两位小数并显示正负号
- df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})
- # 应用 lambda
- df.style.format({"B": lambda x: "±{:.2f}".format(abs(x))})
- # 缺失值的显示格式
- df.style.format("{:.2%}", na_rep="-")
- # 替换空值,精度保留3位小数(1.3.0+)
- df.style.format(na_rep='MISS', precision=3)
- # 转义方法,还可以用 LaTeX(1.3.0+)
- # 对float数据的整数个小数部分的分隔,默认是小数点(1.3.0+)
- df.loc[:,'Q2':].astype(float).style.format(decimal=';')
- # 处理内置样式函数的缺失值
- df.style.highlight_max().format(None, na_rep="-")
- # 常用的格式
- {'a': '¥{0:,.0f}', # 货币符号
- 'b': '{:%Y-%m}', # 年月
- 'c': '{:.2%}', # 百分号
- 'd': '{:,f}', # 千分位
- 'e': str.upper} # 大写
#综合案例
- # 链式方法使用格式
- (df.head(15)
- .head(10)
- .assign(avg=df.mean(axis=1, numeric_only=True)/100) # 增加平均值百分比
- .assign(diff=lambda x: x.avg.diff()) # 和前位同学差值
- .style
- .format({'name': str.upper})
- .format({'avg': "{:.2%}"})
- .format({'diff': "¥{:.2f}"}, na_rep="-")
- )

#标题 caption
- #给表格一个标题:
- df.head().style.set_caption('学生成绩表')

#精度 Precision
- #可以设置全局的数据精度,即保留小数的位数。
- # 保留两个小数
- df.head().style.set_precision(2)
- # 等同于
- df.head().round(2).style
-
- #案例
- df.assign(mean=df.mean(1)).head().style.set_precision(2)

#缺失值 Missing values
- #缺失值的统一设置。
- df.style.set_na_rep("暂无")
#隐藏索引和列
- # 不输出索引
- df.style.hide_index()
- # 不输出指定列
- df.style.hide_columns(['C','D'])
样式也可以像df做计算一样使用函数进行整体设置,例如下面将每行最大值字体置为红色:
- #最大值字体置为红色:
-
- # 最大值显示红色
- def highlight_max(x):
- return ['color: red' if v == x.max() else '' for v in x]
-
- # 应用函数
- df.style.apply(highlight_max)
- # 按行应用
- df.head().loc[:,'Q1':'Q4'].style.apply(highlight_max, axis=1)

#以下所有大于90分的格子背景为黄色:
- #以下所有大于90分的格子背景为黄色:
- yellow_css = 'background-color: yellow'
- sfun = lambda x: yellow_css if type(x) == int and x > 90 else ''
- df.style.applymap(sfun)
-
- #subset 参数可以指定部分内容应用样式规则:
- df.head().style.applymap(sfun, subset=['Q1', 'Q2'])

#可以将其他的样式利用到新的表格中:
- # 将 df 的样式赋值给变量
- style1 = df.style.applymap(color_negative_red)
- # df2 的样式为 style2
- style2 = df2.style
- # style2 使用 style1的样式
- style2.use(style1.export())
- # df.style.clear() 会返回 None,清除所有样式。
- # 定义为一个变量
- dfs = df.loc[:,'Q1':'Q4'].style.apply(highlight_max)
- dfs.clear() # 清除
- dfs # 此时 dfs 不带任何样式,但还是 Styler 对象
#样式导出 Excel 后会保留原来定义的样式。下面是一些参数和用法
- # 导出 Excel
- df.style.to_excel('gairuo.xlsx')
- # 使用指定引擎,openpyxl 的样式兼容更好些
- df.style.to_excel('gairuo.xlsx', engine='openpyxl')
- # 指定标签页名称,sheet name
- dfs.to_excel('gairuo.xlsx', sheet_name='Sheet1')
- # 缺失值的指定
- dfs.to_excel('gairuo.xlsx', na_rep='-')
- # 浮点数字格式, 下例将 0.1234 转为 0.12
- dfs.to_excel('gairuo.xlsx', float_format="%.2f")
- # 只要这两例
- dfs.to_excel('gairuo.xlsx', columns=['Q1', 'Q2'])
- # 不带表头
- dfs.to_excel('gairuo.xlsx', header=False)
- # 不带索引
- dfs.to_excel('gairuo.xlsx', index=False)
- # 指定索引,多个为多层索引
- dfs.to_excel('gairuo.xlsx', index_label=['team', 'name'])
- # 从哪行取,从哪列取
- dfs.to_excel('gairuo.xlsx', startrow=10, startcol=3)
- # 不合并单元格
- dfs.to_excel('gairuo.xlsx', merge_cells=False)
- # 指定编码
- dfs.to_excel('gairuo.xlsx', encoding='utf-8')
- # 无穷大表示法(Excel中没有无穷大的本机表示法)
- dfs.to_excel('gairuo.xlsx', inf_rep='inf')
- # 在错误日志中显示更多信息
- dfs.to_excel('gairuo.xlsx', verbose=True)
- # 指定要冻结的最底行和最右列
- dfs.to_excel('gairuo.xlsx', freeze_panes=(0,2))
Styler.render() 可以输出样式的 Html 代码,它可以传入以下参数:
head cellstyle body uuid precision table_styles caption table_attributes
- df.style.render()
- # 过虑换行取部分,增加可读性
- df.style.highlight_null().render().split('\n')[:10]
-
- # 在 notebook 中可以会用来解析展示生成的 html
- from IPython.display import HTML
- HTML(df.style.render())
#注意,Styler.render() 无法导出 html 文件,1.3.0 版本增加了 df.style.to_html() 方法,可以让我们更方便地输出 html 文档:
- # 输出表格和CSS样式的字符串
- df.style.to_html()
- # 输出完整的 html 代码字符串
- df.style.to_html(doctype_html=True)
- # 输出为html文件
- df.style.to_html('table.html')
- # 不输出 CSS 样式
- df.style.render(exclude_styles=True)
- # 给 table 标签加 style="color:red" 属性字符
- df.style.render(table_attributes='style="color:red"')