pandas.io.formats.style.Styler.apply#

Styler.apply(func, axis=0, subset=None, **kwargs)[源代码]#

按列、按行或按表应用css样式函数。

使用结果更新HTML表示形式。

参数
func功能

func 应该参加一个系列赛,如果 axis 在……里面 [0,1] 并返回相同长度的类似列表的对象,或返回不一定具有相同长度的Series,并考虑有效的索引标签 subsetfunc 如果出现以下情况,则应采用DataFrame axisNone 并返回具有相同形状的ndarray或不一定具有相同形状的DataFrame,并考虑有效的索引和列标签 subset

在 1.3.0 版更改.

在 1.4.0 版更改.

axis{0或‘index’,1或‘Columns’,无},默认0

应用于每列 (axis=0'index' ),到每一行 (axis=1'columns' ),或使用以下命令一次性访问整个DataFrame axis=None

subset标签、类似数组、索引切片、可选

有效的2D输入到 DataFrame.loc[<subset>] ,或者,在1D输入或单键的情况下, DataFrame.loc[:, <subset>] 对列进行优先排序的位置,以限制 data在此之前 应用该函数。

**kwargsDICT

传递给 func

退货
self造型师

参见

Styler.applymap_index

对标题元素应用一个css样式函数。

Styler.apply_index

对标头逐级应用css样式函数。

Styler.applymap

以元素方式应用一个css样式函数。

注意事项

的输出元素 func 应为字符串形式的CSS样式,格式为‘ATTRIBUTE:VALUE;ATTRIBUTE 2:VALUE2;...’或者,如果不对该元素应用任何内容,则为空字符串或 None

这类似于 DataFrame.apply ,除了 axis=None 将函数一次应用于整个DataFrame,而不是按列或按行应用。

示例

>>> def highlight_max(x, color):
...     return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None)
>>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
>>> df.style.apply(highlight_max, color='red')  
>>> df.style.apply(highlight_max, color='blue', axis=1)  
>>> df.style.apply(highlight_max, color='green', axis=None)  

使用 subset 将应用程序限制为单列或多列

>>> df.style.apply(highlight_max, color='red', subset="A")
...  
>>> df.style.apply(highlight_max, color='red', subset=["A", "B"])
...  

使用2D输入以 subset 除列外还选择行的步骤

>>> df.style.apply(highlight_max, color='red', subset=([0,1,2], slice(None)))
...  
>>> df.style.apply(highlight_max, color='red', subset=(slice(0,5,2), "A"))
...  

使用返回长度不等但包含有效索引标签的Series/DataFrame的函数

>>> df = pd.DataFrame([[1, 2], [3, 4], [4, 6]], index=["A1", "A2", "Total"])
>>> total_style = pd.Series("font-weight: bold;", index=["Total"])
>>> df.style.apply(lambda s: total_style)  

看见 Table Visualization 用户指南,了解更多详细信息。