当前pandas版本为:1.2.5。
pandas数据结构在Jupyter Notebook中以表格形式呈现。这些表格的格式化依赖于pandas中的Styler对象。Dateframe.style属性返回值为Styler对象。
Styler对象的方法的返回值大部分还是Styler对象,Styler对象支持链式调用,这样就可以将多种样式叠加在一起。
1. 显示值格式化
pandas在notebook中的值分为显示值和实际值。Styler.format()方法可以格式化显示值。
Styler.format()方法的签名如下:Styler.format(formatter, subset=None, na_rep=None)
Styler.format()方法具有以下参数:
formatter:格式。类型为字符串、可调用对象、字典或None。默认值为None。- 字符串:格式化字符串。
- 字典:键为列索引,值为对应列的格式化字符串。
- 可调用对象:参数为单独的一个值即元素,返回值为字符串。
- 可调用对象字典:键为列索引,值为可调用对象。
subset:用于指定生效范围,即DataFrame的索引。na_rep:缺失值的显示值。类型为字符串。默认为None,即不作任何更改。
Styler.format()方法的返回值为Styler对象。
案例:Styler.format()方法formatter参数演示
本案例案例中,formatter参数分别采用字符串、字典、可调用对象字典对DataFrame进行格式化。
首先对设置所有单元格均保留小数点后2位数字,然后再设置b列显示为百分比保留2位小数,最后将c列字符串设置为大写。
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])
df['c'] =<

本文介绍Pandas Styler对象的高级用法,包括显示值格式化、内置显示值格式化方法、表格外观设置及样式复用等。通过实例演示如何美化DataFrame的数据展示。
最低0.47元/天 解锁文章
4593





