pandas.io.formats.style.Styler.format_index#
- Styler.format_index(formatter=None, axis=0, level=None, na_rep=None, precision=None, decimal='.', thousands=None, escape=None, hyperlinks=None)[源代码]#
设置索引标签或列标题的文本显示值的格式。
1.4.0 新版功能.
- 参数
- formatter字符串、可调用、判定或无
对象以定义值的显示方式。请参见备注。
- axis{0,“索引”,1,“列”}
是将格式化程序应用于索引标题还是列标题。
- levelInt、str、list
要在其上应用通用格式化程序的级别。
- na_rep字符串,可选
缺失值的表示形式。如果
na_rep
为None,则不应用特殊格式。- precision整型,可选
用于显示的浮点精度,如果不是由指定的
formatter
。- decimal字符串,默认“。
用作浮点数、复数和整数的小数分隔符的字符。
- thousands字符串,可选,默认为无
用作浮点数、复数和整数的千位分隔符的字符。
- escape字符串,可选
使用‘html’替换字符
&
,<
,>
,'
,以及"
在具有HTML安全序列的单元格显示字符串中。使用‘LaTeX’替换字符&
,%
,$
,#
,_
,{{
,}}
,~
,^
,以及\
在具有 Latex 安全序列的单元格显示字符串中。逃跑之前就已经做过了formatter
。- hyperlinks{“html”,“LaTeX”},可选
转换包含https://,http://,ftp://或www的字符串模式。如果是“html”,则将<a>标记设置为可点击的URL超链接;如果是“laTeX”,则将LaTeXhref命令转换为可点击URL超链接。
- 退货
- self造型师
参见
Styler.format
设置数据单元格的文本显示值的格式。
注意事项
该方法分配格式化函数,
formatter
,添加到DataFrame的索引或列标题中的每个级别标签。如果formatter
是None
,则使用默认格式化程序。如果是可调用,则该函数应将标签值作为输入,并返回可显示的表示形式,如字符串。如果formatter
作为字符串给出,则假定这是有效的Python格式规范,并包装为可调用的string.format(x)
。如果一个dict
键应该与多索引级别编号或名称相对应,并且值应该是字符串或可调用的,如上所述。默认格式化程序当前使用Pandas显示精度表示浮点数和复数,除非使用
precision
争论在这里。默认格式化程序不会调整缺失值的表示形式,除非na_rep
参数被使用。这个
level
参数定义要将该方法应用于多重索引的哪些级别。如果formatter
参数以DICT形式给出,但不包括级别参数中的所有级别,则这些未指定的级别将应用默认格式化程序。格式化程序字典中明确排除在Level参数之外的任何级别都将被忽略。在使用
formatter
字符串数据类型必须兼容,否则将引发 ValueError 都会被举起。警告
Styler.format_index 在使用输出格式时被忽略 Styler.to_excel ,因为Excel和Python具有固有的不同格式结构。但是,可以使用 number-format 用于强制设置Excel允许的格式的伪CSS属性。请参阅的文档 Styler.format 。
示例
使用
na_rep
和precision
使用默认设置formatter
>>> df = pd.DataFrame([[1, 2, 3]], columns=[2.0, np.nan, 4.0]) >>> df.style.format_index(axis=1, na_rep='MISS', precision=3) 2.000 MISS 4.000 0 1 2 3
使用
formatter
关于级别中一致数据类型的规范>>> df.style.format_index('{:.2f}', axis=1, na_rep='MISS') 2.00 MISS 4.00 0 1 2 3
使用默认设置
formatter
对于未指明的级别>>> df = pd.DataFrame([[1, 2, 3]], ... columns=pd.MultiIndex.from_arrays([["a", "a", "b"],[2, np.nan, 4]])) >>> df.style.format_index({0: lambda v: upper(v)}, axis=1, precision=1) ... A B 2.0 nan 4.0 0 1 2 3
使用可调用的
formatter
功能。>>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT' >>> df.style.format_index(func, axis=1, na_rep='MISS') ... STRING STRING FLOAT MISS FLOAT 0 1 2 3
使用
formatter
使用HTML语言escape
和na_rep
。>>> df = pd.DataFrame([[1, 2, 3]], columns=['"A"', 'A&B', None]) >>> s = df.style.format_index('$ {0}', axis=1, escape="html", na_rep="NA") ... <th .. >$ "A"</th> <th .. >$ A&B</th> <th .. >NA</td> ...
使用
formatter
使用 Latexescape
。>>> df = pd.DataFrame([[1, 2, 3]], columns=["123", "~", "$%#"]) >>> df.style.format_index("\\textbf{{{}}}", escape="latex", axis=1).to_latex() ... \begin{tabular}{lrrr} {} & {\textbf{123}} & {\textbf{\textasciitilde }} & {\textbf{\$\%\#}} \\ 0 & 1 & 2 & 3 \\ \end{tabular}