pandas.io.formats.style.Styler.pipe #
- 造型器。管道( func , * args , ** kwargs ) [来源] #
应用,并返回结果。
func(self, *args, **kwargs)
- 参数:
- 函数函数
应用于 Styler 的函数。或者, 元组是一个字符串,指示需要样式器的关键字。
(callable, keyword)
keyword
callable
- *参数可选
参数传递给func。
- **kwargs可选
传递到 的关键字参数的字典
func
。
- 返回:
- 目的
返回的值
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))
特别是,这允许用户定义采用样式器对象以及其他参数的函数,并在进行样式更改(例如调用
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")
由于该方法返回一个
Styler
对象,因此它可以与其他方法链接,就像直接应用底层荧光笔一样。>>> (df.style.format("{:.1f}") ... .pipe(some_highlights, min_color="green") ... .highlight_between(left=2, right=5))
高级使用
有时可能需要预定义样式函数,但在这些函数依赖于样式器、数据或上下文的情况下。由于
Styler.use
和Styler.export
被设计为不依赖于数据,因此它们不能用于此目的。此外,Styler.apply
和Styler.format
type 方法不支持上下文感知,因此解决方案是使用pipe
动态包装此功能。假设我们想要编写一个通用样式函数来突出显示 MultiIndex 的最终级别。索引中的级别数是动态的,因此我们需要上下文
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)
另外,假设我们想要突出显示该列中缺少任何数据的列标题。在这种情况下,我们需要数据对象本身来确定对列标题的影响。
>>> 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)