pandas.io.formats.style.Styler.pipe#

Styler.pipe(func, *args, **kwargs)[源代码]#

应用 func(self, *args, **kwargs) ,并返回结果。

参数
func功能

函数应用于Styler。或者,一个 (callable, keyword) 元组所在位置 keyword 是一个字符串,它指示 callable 期待着造型师的到来。

*args可选

传递给 func

**kwargs可选

传入的关键字参数词典 func

退货
object

由返回的值 func

参见

DataFrame.pipe

DataFrame的类似方法。

Styler.apply

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

注意事项

喜欢 DataFrame.pipe() ,这种方法可以简化几个用户定义函数对样式器的应用。而不是写:

f(g(df.style.format(precision=3), arg1=a), arg2=b, arg3=c)

用户可以写道:

(df.style.format(precision=3)
   .pipe(g, arg1=a)
   .pipe(f, arg2=b, arg3=c))

具体地说,这允许用户定义接受Style对象以及其他参数的函数,并在进行样式更改(如调用 Styler.apply()Styler.set_properties() )。

示例

常用法

一种常见的使用模式是预定义样式操作,这些操作可以很容易地应用于单个 pipe 打电话。

>>> def some_highlights(styler, min_color="red", max_color="blue"):
...      styler.highlight_min(color=min_color, axis=None)
...      styler.highlight_max(color=max_color, axis=None)
...      styler.highlight_null()
...      return styler
>>> df = pd.DataFrame([[1, 2, 3, pd.NA], [pd.NA, 4, 5, 6]], dtype="Int64")
>>> df.style.pipe(some_highlights, min_color="green")  
../../_images/df_pipe_hl.png

由于该方法返回一个 Styler 对象,它可以与其他方法链接在一起,就像直接应用基础高亮笔一样。

>>> df.style.format("{:.1f}")
...         .pipe(some_highlights, min_color="green")
...         .highlight_between(left=2, right=5)  
../../_images/df_pipe_hl2.png

高级用途

有时可能需要预定义样式函数,但在这些函数依赖于样式器、数据或上下文的情况下。自.以来 Styler.useStyler.export 被设计为不依赖于数据,因此不能用于此目的。此外, Styler.applyStyler.format 类型方法不能识别上下文,因此解决方案是使用 pipe 以动态包装此功能。

假设我们想要编写一个通用样式函数来突出显示多重索引的最后一级。索引中的级别数量是动态的,因此我们需要 Styler 用于定义级别的上下文。

>>> def highlight_last_level(styler):
...     return styler.apply_index(
...         lambda v: "background-color: pink; color: yellow", axis="columns",
...         level=styler.columns.nlevels-1
...     )  
>>> df.columns = pd.MultiIndex.from_product([["A", "B"], ["X", "Y"]])
>>> df.style.pipe(highlight_last_level)  
../../_images/df_pipe_applymap.png

此外,假设我们希望突出显示列标题(如果该列中有任何缺失的数据)。在这种情况下,我们需要数据对象本身来确定对列标题的影响。

>>> def highlight_header_missing(styler, level):
...     def dynamic_highlight(s):
...         return np.where(
...             styler.data.isna().any(), "background-color: red;", ""
...         )
...     return styler.apply_index(dynamic_highlight, axis=1, level=level)
>>> df.style.pipe(highlight_header_missing, level=1)  
../../_images/df_pipe_applydata.png