• Pandas数据分析25——pandas数据框样式设置


     参考书目:《深入浅出Pandas:利用Python进行数据处理与分析》


    pandas里面的数据框也可以像excel那样做条件样式,并且给予一定的可视化能力,比如找出每行或者每列的最大值标红,低于平均值的数据标黑等等......对于数据科学家使用jupyternotebook处理数据是很方便可视化的。下面一起学习一下这些样式的实现。

    还是先导入包和读取案例数据

    1. import numpy as np
    2. import pandas as pd
    3. data = 'https://www.gairuo.com/file/data/dataset/team.xlsx'
    4. df = pd.read_excel(data)

    pandas里面的样式靠df.style这个类实现,首先我们看看他的类型

    type(df.style)

     下面我们会用这个类的方法去实现df数据框的样式调整。


    内置样式

    空值高亮 highlight_null

    #对为空的值,高亮标示。

    1. df.iloc[1,1] = np.NaN # 修改一个值空
    2. df.head().style.highlight_null() # 默认红色

     #可以指定颜色:

    1. # 使用颜色名
    2. df.head().style.highlight_null(null_color='blue')
    3. # 使用颜色值
    4. df.head().style.highlight_null(null_color='#ccc')

     


    最大最小值高亮

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

     # 同时使用+指定颜色

    1. (df.head()
    2. .style.highlight_max(color='lime') # 最大值高亮
    3. .highlight_min(color='blue') # 最小值
    4. )

     # 指定行上最大最小

    1. (df.head()
    2. .style.highlight_max(color='wheat', axis=1) # 最大值高亮, 粉红
    3. .highlight_min(axis=1,color='lightsteelblue') # 最小值,浅蓝
    4. )

     #也可以作用于指定行:

    1. # 只对 Q1 起作用
    2. df.style.highlight_min(subset=['Q1'])
    3. df.style.highlight_min(subset=['Q1', 'Q2']) # 两列
    4. # 按行,只在这两列进行
    5. df.head(10).style.highlight_min(axis=1, subset=['Q1','Q2'])

     


    区间高亮 highlight_between

    #对指定区间的值进行高亮标注显示,可以是数字,也可以是时间(1.3.0 版本+):

    1. # Q4 列的 60 到 100 高亮
    2. df.style.highlight_between(left=60, right=100, subset=['Q4'])
    3. # axis=None 并将 left 参数作为与输入数据帧匹配的数组提供,常量 right
    4. df.style.highlight_between(left=[[2,2,3],[2,2,3],[3,3,3]], right=3.5,axis=None, color="#fffd75")
    5. # 指定 css 样式
    6. df.style.highlight_between(left=1.5, right=3.5,props='font-weight:bold;color:#e83e8c')

    分位数高亮 highlight_quantile

    #使用样式高亮显示分位数定义的值(1.3.0 版本+),就是说把指定分位区间的数据高亮。使用 axis=None 对所有集合数据应用分位数。

    1. df = pd.DataFrame(np.arange(10).reshape(2,5) + 1)
    2. # 将后四分位的数据高亮,即后 3/4 的数据
    3. df.style.highlight_quantile(axis=None, q_left=0.25, color="#fffd75")
    4. # 按行或按列高亮显示分位数,在本例中按行高亮显示
    5. df.style.highlight_quantile(axis=1, q_left=0.8, color="#fffd75")
    6. # 使用 props 而不是默认的背景颜色
    7. df.style.highlight_quantile(axis=None, q_left=0.2, q_right=0.8,props='font-weight:bold;color:#e83e8c')

    文本颜色渐变 text_gradient

    以渐变样式为文本着色。文本颜色根据每列、每行或每帧中的数据或给定的渐变图谱确定。依赖 matplotlib。

    语法是:Styler.text_gradient(cmap='PuBu', low=0, high=0,axis=0, subset=None, vmin=None, vmax=None, gmap=None) 示例如下:

    1. # 数据集
    2. df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
    3. data=[["Stockholm", 21.6, 5.0, 3.2],
    4. ["Oslo", 22.4, 13.3, 3.1],
    5. ["Copenhagen", 24.5, 0.0, 6.7]])
    6. # 按列着色显示值,axis=0,预选数值列
    7. df.style.text_gradient(axis=0)
    8. # 使用 axis=None 对所有值进行整体着色
    9. df.style.text_gradient(axis=None)
    10. # 从低值和高值颜色着色
    11. df.style.text_gradient(axis=None, low=0.75, high=1.0)
    12. # 手动设置vmin和vmax梯度阈值
    13. df.style.text_gradient(axis=None, vmin=6.7, vmax=21.6)
    14. # 设置 gmap 并使用另一个 cmap 应用于所有列
    15. df.style.text_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')
    16. # 设置数据帧的渐变贴图(即axis=None),我们需要
    17. # 显式地声明子集以匹配 gmap 形状
    18. gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
    19. df.style.text_gradient(axis=None, gmap=gmap,
    20. cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)'] )

     


    背景渐变 background_gradient

     #根据数值的大小背景颜色呈现梯度渐变,越深表示越大,越浅表示越小,类似于 Excel 的中的色阶样式。

    1. # 数字类型按列背景渐变
    2. df.style.background_gradient()
    3. # 指定列,指定颜色系列
    4. df.style.background_gradient(subset=['Q1'], cmap='BuGn')
    5. # 低百分比和高百分比范围, 更换颜色时避免使用所有色域
    6. df.style.background_gradient(low=0.6, high=0)
    7. # 内容的颜色,取 0-1(深色到浅色),方便突显出文本
    8. df.style.background_gradient(text_color_threshold=0.5)
    9. # 颜色应用的取值范围,不在这个范围的不应用
    10. df.head().style.background_gradient(vmin=60, vmax=90)

     #以下是一个综合使用示例:

    1. # 链式方法使用样式
    2. (df.head(10)
    3. .style
    4. .background_gradient(subset=['Q1'], cmap='spring') # 指定色系
    5. .background_gradient(subset=['Q2'], vmin=60, vmax=100) # 指定应用值区间
    6. .background_gradient(subset=['Q3'], low=0.6, high=0) # 高低百分比范围
    7. .background_gradient(subset=['Q4'], text_color_threshold=0.9) # 文本色深
    8. )

     


    条形图 bar

      #条形图在表格里一般以横向柱状图的形式代表这个值的大小。

    1. # 基本使用,默认将数字应用
    2. df.head(10).style.bar()

     其他参数

    1. # 指定应用范围
    2. df.style.bar(subset=['Q1'])
    3. # 定义颜色
    4. df.style.bar(color='green')
    5. df.style.bar(color='#ff11bb')
    6. # 以向进行计算展示
    7. df.style.bar(axis=1)
    8. # 样式在格中的占位百分比,0-100, 100占满
    9. df.style.bar(width=80)
    10. # 对齐方式:
    11. # ‘left’ 最小值开始,
    12. # ‘zero’ 0值在中间,
    13. # ’mid’ (max-min)/2 值在中间,负(正)值0在右(左)
    14. df.style.bar(align='mid')
    15. # 大小基准值
    16. df.style.bar(vmin=60, vmax=100)

    #以下是一个综合示例:

    1. (df.head(10)
    2. .assign(avg=df.mean(axis=1, numeric_only=True)) # 增加平均值
    3. .assign(diff=lambda x: x.avg.diff()) # 和前位同学差值
    4. .style
    5. .bar(color='yellow', subset=['Q1'])
    6. .bar(subset=['avg'],
    7. width=90,
    8. align='mid',
    9. vmin=60, vmax=100,
    10. color='#5CADAD')
    11. .bar(subset=['diff'],
    12. color=['#bbf9ce','#ffe4e4',], # 上涨下降的颜色
    13. vmin=0, vmax=30, # 范围定以0为基准的上下30
    14. align='zero') # 0 值居中
    15. )

     


    显示格式

    我们在最终输出数据查看时,需要对数据进行相应的格式化,常见的如加货币符号、加百分号、增加千分位等,目的是让计数更加场景化,明确列表一定的业务意义。

    Styler.format 是专门用来处理格式的方法。

    语法结构 Styler.format(self, formatter,subset=None, na_rep: Union[str,NoneType]=None)

    df.head().style.format("[{}]")  #给所有数据加上[]

    #用法 

    1. # 百分号,类似 29.57%
    2. df.style.format("{:.2%}")
    3. # 指定列全变为大写
    4. df.style.format({'name': str.upper})
    5. # B 保留四位,D 两位小数并显示正负号
    6. df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})
    7. # 应用 lambda
    8. df.style.format({"B": lambda x: "±{:.2f}".format(abs(x))})
    9. # 缺失值的显示格式
    10. df.style.format("{:.2%}", na_rep="-")
    11. # 替换空值,精度保留3位小数(1.3.0+)
    12. df.style.format(na_rep='MISS', precision=3)
    13. # 转义方法,还可以用 LaTeX(1.3.0+)
    14. df.style.format('{0}', escape="html")
    15. # 对float数据的整数个小数部分的分隔,默认是小数点(1.3.0+)
    16. df.loc[:,'Q2':].astype(float).style.format(decimal=';')
    17. # 处理内置样式函数的缺失值
    18. df.style.highlight_max().format(None, na_rep="-")
    19. # 常用的格式
    20. {'a': '¥{0:,.0f}', # 货币符号
    21. 'b': '{:%Y-%m}', # 年月
    22. 'c': '{:.2%}', # 百分号
    23. 'd': '{:,f}', # 千分位
    24. 'e': str.upper} # 大写

    #综合案例

    1. # 链式方法使用格式
    2. (df.head(15)
    3. .head(10)
    4. .assign(avg=df.mean(axis=1, numeric_only=True)/100) # 增加平均值百分比
    5. .assign(diff=lambda x: x.avg.diff()) # 和前位同学差值
    6. .style
    7. .format({'name': str.upper})
    8. .format({'avg': "{:.2%}"})
    9. .format({'diff': "¥{:.2f}"}, na_rep="-")
    10. )

     


     

     样式高级操作

    常用操作

    #标题 caption

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

     #精度 Precision

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

     #缺失值 Missing values

    1. #缺失值的统一设置。
    2. df.style.set_na_rep("暂无")

    #隐藏索引和列

    1. # 不输出索引
    2. df.style.hide_index()
    3. # 不输出指定列
    4. df.style.hide_columns(['C','D'])

    函数应用

     样式也可以像df做计算一样使用函数进行整体设置,例如下面将每行最大值字体置为红色:

    1. #最大值字体置为红色:
    2. # 最大值显示红色
    3. def highlight_max(x):
    4. return ['color: red' if v == x.max() else '' for v in x]
    5. # 应用函数
    6. df.style.apply(highlight_max)
    7. # 按行应用
    8. df.head().loc[:,'Q1':'Q4'].style.apply(highlight_max, axis=1)

     #以下所有大于90分的格子背景为黄色:

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

     


    样式复用

    #可以将其他的样式利用到新的表格中:

    1. # 将 df 的样式赋值给变量
    2. style1 = df.style.applymap(color_negative_red)
    3. # df2 的样式为 style2
    4. style2 = df2.style
    5. # style2 使用 style1的样式
    6. style2.use(style1.export())

    样式清除

    1. # df.style.clear() 会返回 None,清除所有样式。
    2. # 定义为一个变量
    3. dfs = df.loc[:,'Q1':'Q4'].style.apply(highlight_max)
    4. dfs.clear() # 清除
    5. dfs # 此时 dfs 不带任何样式,但还是 Styler 对象

     


     

    导出样式

    导出 Excel

    #样式导出 Excel 后会保留原来定义的样式。下面是一些参数和用法

    1. # 导出 Excel
    2. df.style.to_excel('gairuo.xlsx')
    3. # 使用指定引擎,openpyxl 的样式兼容更好些
    4. df.style.to_excel('gairuo.xlsx', engine='openpyxl')
    5. # 指定标签页名称,sheet name
    6. dfs.to_excel('gairuo.xlsx', sheet_name='Sheet1')
    7. # 缺失值的指定
    8. dfs.to_excel('gairuo.xlsx', na_rep='-')
    9. # 浮点数字格式, 下例将 0.1234 转为 0.12
    10. dfs.to_excel('gairuo.xlsx', float_format="%.2f")
    11. # 只要这两例
    12. dfs.to_excel('gairuo.xlsx', columns=['Q1', 'Q2'])
    13. # 不带表头
    14. dfs.to_excel('gairuo.xlsx', header=False)
    15. # 不带索引
    16. dfs.to_excel('gairuo.xlsx', index=False)
    17. # 指定索引,多个为多层索引
    18. dfs.to_excel('gairuo.xlsx', index_label=['team', 'name'])
    19. # 从哪行取,从哪列取
    20. dfs.to_excel('gairuo.xlsx', startrow=10, startcol=3)
    21. # 不合并单元格
    22. dfs.to_excel('gairuo.xlsx', merge_cells=False)
    23. # 指定编码
    24. dfs.to_excel('gairuo.xlsx', encoding='utf-8')
    25. # 无穷大表示法(Excel中没有无穷大的本机表示法)
    26. dfs.to_excel('gairuo.xlsx', inf_rep='inf')
    27. # 在错误日志中显示更多信息
    28. dfs.to_excel('gairuo.xlsx', verbose=True)
    29. # 指定要冻结的最底行和最右列
    30. dfs.to_excel('gairuo.xlsx', freeze_panes=(0,2))

    输出 Html

    Styler.render() 可以输出样式的 Html 代码,它可以传入以下参数:

    head cellstyle body uuid precision table_styles caption table_attributes

    1. df.style.render()
    2. # 过虑换行取部分,增加可读性
    3. df.style.highlight_null().render().split('\n')[:10]
    4. # 在 notebook 中可以会用来解析展示生成的 html
    5. from IPython.display import HTML
    6. HTML(df.style.render())

     #注意,Styler.render() 无法导出 html 文件,1.3.0 版本增加了 df.style.to_html() 方法,可以让我们更方便地输出 html 文档:

    1. # 输出表格和CSS样式的字符串
    2. df.style.to_html()
    3. # 输出完整的 html 代码字符串
    4. df.style.to_html(doctype_html=True)
    5. # 输出为html文件
    6. df.style.to_html('table.html')
    7. # 不输出 CSS 样式
    8. df.style.render(exclude_styles=True)
    9. # 给 table 标签加 style="color:red" 属性字符
    10. df.style.render(table_attributes='style="color:red"')

  • 相关阅读:
    K8S 多集群管理很难?试试 Karmada | K8S Internals 系列第 3 期
    TCPIP网络编程第一章踩坑过程 bind() error connect() error
    合并区间【贪心算法】
    DBus 在Qt和C++中的使用Demo
    C++ 笔记 18 (STL常用容器 - set & multiset)
    随笔记:重新认识 else if
    c++ 学习 之 运算符重载
    MySQL常见关键字函数
    【设计模式】六、【创建性模式】揭秘单例模式:从生活例子到Java代码
    ue5 lyra的角色动画系统 持续更新中。。。。
  • 原文地址:https://blog.csdn.net/weixin_46277779/article/details/126344626