pandas.io.formats.style.Styler.concat#

Styler.concat(other)[源代码]#

附加另一个 Styler 以将输出合并为单个表格。

在 1.5.0 版本加入.

Parameters:
otherStyler

已经过样式和格式化处理的其他 Styler 对象。此 Styler 的数据必须与原始数据具有相同的列,并且索引级别数也必须相同才能正确渲染。

Returns:
Styler

Notes

此方法的目的是用其他可能有用的度量来扩展现有的样式化数据框,但这些度量可能不符合原始数据框的结构。例如,添加一个副总计行,或显示均值、方差或计数等度量。

使用 applymapapply_indexmap_index 应用的样式,以及使用 formatformat_index 应用的格式将得以保留。

警告

只有 to_htmlto_stringto_latex 输出方法目前支持连接的 Styler。

其他输出方法,包括 to_excel**不支持**连接的 Styler。

应注意以下几点:

  • table_stylestable_attributescaptionuuid 都继承自原始 Styler,而不是 other

  • 隐藏的列和隐藏的索引级别将从原始 Styler 继承。

  • css 将从原始 Styler 继承,键 datarow_headingrow 的值将以 foot0_ 作为前缀。如果链接了更多的 Styler,它们的样式将以 foot1_foot_2 等作为前缀,如果一个连接的样式包含另一个连接的样式,则第二个样式将以 foot{parent}_foot{child}_ 作为前缀。

一个常见的用例是将用户定义的函数与 DataFrame.agg 或通过 DataFrame.describe 描述的统计数据连接起来。请参阅示例。

Examples

一个常见的用例是通过 DataFrame.agg 中计算的方法添加总计行或其他行。

>>> df = pd.DataFrame([[4, 6], [1, 9], [3, 4], [5, 5], [9, 6]],
...                   columns=["Mike", "Jim"],
...                   index=["Mon", "Tue", "Wed", "Thurs", "Fri"])
>>> styler = df.style.concat(df.agg(["sum"]).style)  
../../_images/footer_simple.png

由于连接的对象是 Styler,因此可以使用现有功能对其进行条件格式化,如同对原始 Styler 一样。

>>> descriptors = df.agg(["sum", "mean", lambda s: s.dtype])
>>> descriptors.index = ["Total", "Average", "dtype"]
>>> other = (descriptors.style
...          .highlight_max(axis=1, subset=(["Total", "Average"], slice(None)))
...          .format(subset=("Average", slice(None)), precision=2, decimal=",")
...          .map(lambda v: "font-weight: bold;"))
>>> styler = (df.style
...             .highlight_max(color="salmon")
...             .set_table_styles([{"selector": ".foot_row0",
...                                 "props": "border-top: 1px solid black;"}]))
>>> styler.concat(other)  
../../_images/footer_extended.png

other 的索引级别少于原始 Styler 时,可以在 other 中扩展索引,使用占位符级别。

>>> df = pd.DataFrame([[1], [2]],
...                   index=pd.MultiIndex.from_product([[0], [1, 2]]))
>>> descriptors = df.agg(["sum"])
>>> descriptors.index = pd.MultiIndex.from_product([[""], descriptors.index])
>>> df.style.concat(descriptors.style)