表格可视化#

本节演示如何使用 Styler 类可视化表格数据。有关使用图表进行可视化的信息,请参阅 图表可视化。本文档以 Jupyter Notebook 的形式编写,您可以在 此处 查看或下载。

Styler 对象和自定义显示#

样式和输出显示自定义应在 DataFrame 中的数据处理之后进行。如果对 DataFrame 进行了进一步更改,Styler不会动态更新。 DataFrame.style 属性是一个返回 Styler 对象的属性。它定义了一个 _repr_html_ 方法,因此它会在 Jupyter Notebook 中自动渲染。

Styler 对象虽然可以用于大型数据,但主要设计用于小型数据,目前支持输出到以下格式:

  • HTML

  • LaTeX

  • 字符串(以及扩展的 CSV)

  • Excel

  • (JSON 目前不可用)

其中前三种格式具有用于格式化和自定义输出的显示自定义方法。这些方法包括:

格式化显示#

格式化值#

在数据值和索引或列标题中,Styler 会区分显示值和实际值。要控制显示值,文本将作为字符串打印在每个单元格中,我们可以使用 .format().format_index() 方法,根据 格式说明符字符串 或接受单个值并返回字符串的可调用对象来操作此文本。可以为整个表、索引、单个列或 MultiIndex 级别定义此设置。我们也可以覆盖索引名称。

此外,format 函数还有一个 precision 参数,专门用于格式化浮点数,以及 decimalthousands 分隔符以支持其他语言环境,一个 na_rep 参数用于显示缺失数据,以及 escapehyperlinks 参数以帮助显示安全的 HTML 或安全的 LaTeX。默认格式化程序配置为采用 pandas 的全局选项,例如 styler.format.precision 选项,可通过 with pd.option_context('format.precision', 2): 进行控制。

[1]:
import pandas as pd
import numpy as np

df = pd.DataFrame(
    {"strings": ["Adam", "Mike"], "ints": [1, 3], "floats": [1.123, 1000.23]}
)
df.style.format(precision=3, thousands=".", decimal=",").format_index(
    str.upper, axis=1
).relabel_index(["row 1", "row 2"], axis=0)
[1]:
  字符串 整数 浮点数
第 1 行 Adam 1 1,123
第 2 行 Mike 3 1.000,230

使用 Styler 操纵显示是一个有用的功能,因为维护索引和数据值以用于其他目的可以提供更大的控制。您不必覆盖 DataFrame 即可按您喜欢的方式显示它。以下是一个在使用格式化函数的同时,仍然依赖底层数据进行索引和计算的更全面的示例。

[2]:
weather_df = pd.DataFrame(
    np.random.default_rng().random((10, 2)) * 5,
    index=pd.date_range(start="2021-01-01", periods=10),
    columns=["Tokyo", "Beijing"],
)


def rain_condition(v):
    if v < 1.75:
        return "Dry"
    elif v < 2.75:
        return "Rain"
    return "Heavy Rain"


def make_pretty(styler):
    styler.set_caption("Weather Conditions")
    styler.format(rain_condition)
    styler.format_index(lambda v: v.strftime("%A"))
    styler.background_gradient(axis=None, vmin=1, vmax=5, cmap="YlGnBu")
    return styler


weather_df
[2]:
东京 北京
2021-01-01 3.543874 0.496939
2021-01-02 4.081077 0.276419
2021-01-03 1.305635 4.647819
2021-01-04 1.077516 0.920652
2021-01-05 0.238458 3.353479
2021-01-06 3.889160 1.659478
2021-01-07 2.978732 1.028194
2021-01-08 4.322752 0.984307
2021-01-09 2.980149 3.685912
2021-01-10 0.927475 2.643055
[3]:
weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
[3]:
天气状况
  东京 北京
星期一
星期二 大雨
星期三 大雨
星期四 大雨
星期五 大雨

隐藏数据#

索引和列标题可以完全隐藏,也可以选择性地排除您希望排除的行或列。这两种选项都使用相同的方法来实现。

通过调用不带参数的 .hide() 可以从渲染中隐藏索引,这在索引是基于整数时可能很有用。类似地,通过调用不带其他参数的 .hide(axis=”columns”) 可以隐藏列标题。

通过调用相同的 .hide() 方法,并为 subset 参数传入行/列标签、列表状或行/列标签的切片,可以从渲染中隐藏特定的行或列。

隐藏不会改变 CSS 类的整数排列,例如,隐藏 DataFrame 的前两列意味着列类索引仍将从 col2 开始,因为 col0col1 只是被忽略了。

[4]:
df = pd.DataFrame(np.random.default_rng().standard_normal((5, 5)))
df.style.hide(subset=[0, 2, 4], axis=0).hide(subset=[0, 2, 4], axis=1)
[4]:
  1 3
1 -1.300742 -1.779984
3 0.284738 -1.010491

要将该功能反转为显示功能,最佳实践是组合隐藏项的列表。

[5]:
show = [0, 2, 4]
df.style.hide([row for row in df.index if row not in show], axis=0).hide(
    [col for col in df.columns if col not in show], axis=1
)
[5]:
  0 2 4
0 -0.811477 0.068815 -0.030098
2 -2.085428 -1.830522 0.591292
4 -0.959462 -0.079275 0.564172

级联 DataFrame 输出#

如果两个或多个 Styler 对象具有相同的列,则可以将它们级联在一起。这对于显示 DataFrame 的汇总统计信息非常有用,并且经常与 DataFrame.agg 结合使用。

由于级联的对象是 Styler,它们可以独立地进行样式设置,如下所示,并且它们的级联会保留这些样式。

[6]:
summary_styler = (
    df.agg(["sum", "mean"]).style.format(precision=3).relabel_index(["Sum", "Average"])
)
df.style.format(precision=1).concat(summary_styler)
[6]:
  0 1 2 3 4
0 -0.8 0.6 0.1 -1.2 -0.0
1 -0.9 -1.3 0.6 -1.8 0.6
2 -2.1 -0.7 -1.8 -1.1 0.6
3 1.2 0.3 -0.1 -1.0 0.3
4 -1.0 0.2 -0.1 1.3 0.6
总计 -3.528 -0.860 -1.329 -3.806 2.067
平均值 -0.706 -0.172 -0.266 -0.761 0.413

Styler 对象和 HTML#

Styler 最初是为了支持广泛的 HTML 格式选项而构建的。其 HTML 输出会创建一个 HTML <table>,并利用 CSS 样式语言来操纵许多参数,包括颜色、字体、边框、背景等。有关样式设置 HTML 表格的更多信息,请参见 此处。这开箱即用地提供了极大的灵活性,甚至允许 Web 开发人员将 DataFrame 集成到他们现有的用户界面设计中。

下面我们演示默认输出,它看起来非常类似于标准的 DataFrame HTML 表示。但是,即使我们还没有创建任何样式,HTML 已经为每个单元格附加了一些 CSS 类。我们可以通过调用 .to_html() 方法来查看这些,该方法返回原始 HTML 作为字符串,这对于进一步处理或添加到文件非常有用——请继续阅读 更多关于 CSS 和 HTML。本节还将介绍如何将此默认输出转换为更具沟通性的 DataFrame 输出。例如,我们如何构建 s

[7]:
idx = pd.Index(["Tumour (Positive)", "Non-Tumour (Negative)"], name="Actual Label:")
cols = pd.MultiIndex.from_product(
    [["Decision Tree", "Regression", "Random"], ["Tumour", "Non-Tumour"]],
    names=["Model:", "Predicted:"],
)
df = pd.DataFrame(
    [[38.0, 2.0, 18.0, 22.0, 21, np.nan], [19, 439, 6, 452, 226, 232]],
    index=idx,
    columns=cols,
)
df.style
[7]:
模型 决策树 回归 随机
预测 肿瘤 非肿瘤 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签            
肿瘤(阳性) 38.000000 2.000000 18.000000 22.000000 21 nan
非肿瘤(阴性) 19.000000 439.000000 6.000000 452.000000 226 232.000000
[9]:
s
[9]:
用于多种癌症预测模型的混淆矩阵。
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

我们采取的第一步是创建一个 DataFrame 的 Styler 对象,然后通过使用 .hide() 隐藏不需要的列来选择感兴趣的范围。

[10]:
s = df.style.format("{:.0f}").hide(
    [("Random", "Tumour"), ("Random", "Non-Tumour")], axis="columns"
)
s
[10]:
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

添加样式的[]方法#

3 种主要方法可将自定义 CSS 样式添加到 Styler

  • 使用 .set_table_styles() 来控制具有指定内部 CSS 的表格的更广泛区域。尽管表格样式允许添加 CSS 选择器和属性来控制表格的每个单独部分,但它们对于单个单元格的规范来说很不方便。此外,请注意,表格样式无法导出到 Excel。

  • 使用 .set_td_classes() 直接将外部 CSS 类链接到您的数据单元格,或链接由 .set_table_styles() 创建的内部 CSS 类。请参阅 此处。这些不能用于列标题行或索引,也不会导出到 Excel。

  • 使用 .apply().map() 函数将直接的内部 CSS 添加到特定的数据单元格。请参阅 此处。从 v1.4.0 开始,还有直接作用于列标题行或索引的方法:.apply_index().map_index()。请注意,只有这些方法添加的样式才会导出到 Excel。这些方法的工作方式类似于 DataFrame.apply()DataFrame.map()

表格样式#

表格样式足够灵活,可以控制表格的所有单个部分,包括列标题和索引。然而,对于单个数据单元格或任何类型的条件格式化来说,它们可能很难输入,因此我们建议将表格样式用于广泛的样式设置,例如一次设置整行或整列。

表格样式还用于控制可一次应用于整个表格的功能,例如创建通用的悬停功能。只能通过这种方式使用 :hover 伪选择器以及其他伪选择器。

要复制 CSS 选择器和属性(属性值对)的常规格式,例如:

tr:hover {
  background-color: #ffff99;
}

将样式传递给 .set_table_styles() 的必要格式是字典列表,每个字典都有一个 CSS 选择器标签和 CSS 属性。属性可以是 2 元组列表,也可以是常规 CSS 字符串,例如:

[12]:
cell_hover = {  # for row hover use <tr> instead of <td>
    "selector": "td:hover",
    "props": [("background-color", "#ffffb3")],
}
index_names = {
    "selector": ".index_name",
    "props": "font-style: italic; color: darkgrey; font-weight:normal;",
}
headers = {
    "selector": "th:not(.index_name)",
    "props": "background-color: #000066; color: white;",
}
s.set_table_styles([cell_hover, index_names, headers])
[12]:
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

接下来,我们再添加几个针对表格特定部分的样式元素。在此处要小心,因为我们正在链式调用方法,所以我们需要明确指示该方法不要 overwrite 现有样式。

[14]:
s.set_table_styles(
    [
        {"selector": "th.col_heading", "props": "text-align: center;"},
        {"selector": "th.col_heading.level0", "props": "font-size: 1.5em;"},
        {"selector": "td", "props": "text-align: center; font-weight: bold;"},
    ],
    overwrite=False,
)
[14]:
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

作为一个方便的方法(自 1.2.0 版本起),我们还可以将一个字典传递给 .set_table_styles(),该字典包含行或列键。在后台,Styler 只是对键进行索引,并将相应的 .col<m>.row<n> 类添加到给定的 CSS 选择器中。

[16]:
s.set_table_styles(
    {
        ("Regression", "Tumour"): [
            {"selector": "th", "props": "border-left: 1px solid white"},
            {"selector": "td", "props": "border-left: 1px solid #000066"},
        ]
    },
    overwrite=False,
    axis=0,
)
[16]:
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

设置类并链接到外部 CSS#

如果您设计了一个网站,那么您很可能已经有一个外部 CSS 文件来控制其中表格和单元格对象的样式。您可能希望使用这些本地文件,而不是在 Python 中复制所有 CSS(并复制任何维护工作)。

表格属性#

使用 .set_table_attributes() 为主 <table> 添加 class 非常容易。此方法还可以附加内联样式 - 有关更多信息,请参阅 CSS 层次结构

[18]:
out = s.set_table_attributes('class="my-table-cls"').to_html()
print(out[out.find("<table") :][:109])
<table id="T_xyz01" class="my-table-cls">
  <thead>
    <tr>
      <th class="index_name level0" >Model:</th>

数据单元格 CSS 类#

1.2.0 版本新增

.set_td_classes() 方法接受一个 DataFrame,该 DataFrame 的索引和列与底层的 Styler 的 DataFrame 匹配。该 DataFrame 将包含字符串作为 CSS 类,添加到各个数据单元格:<table><td> 元素。而不是使用外部 CSS,我们将内部创建我们的类并将其添加到表格样式中。我们将在关于工具提示的章节中保存添加边框。

[19]:
s.set_table_styles(
    [  # create internal CSS classes
        {"selector": ".true", "props": "background-color: #e6ffe6;"},
        {"selector": ".false", "props": "background-color: #ffe6e6;"},
    ],
    overwrite=False,
)
cell_color = pd.DataFrame(
    [["true ", "false ", "true ", "false "], ["false ", "true ", "false ", "true "]],
    index=df.index,
    columns=df.columns[:4],
)
s.set_td_classes(cell_color)
[19]:
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

Styler 函数#

作用于数据#

我们使用以下方法传递样式函数。这两种方法都接受一个函数(以及一些其他关键字参数),并以某种方式将其应用于 DataFrame,从而渲染 CSS 样式。

  • .map()(逐元素):接受一个接受单个值并返回 CSS 属性-值对字符串的函数。

  • .apply()(按列/行/表):接受一个接受 Series 或 DataFrame 并返回具有相同形状的 Series、DataFrame 或 numpy 数组的函数,其中每个元素都是一个 CSS 属性-值对字符串。此方法根据 axis 关键字参数,一次传递 DataFrame 的每一列或每一行,或者一次传递整个表。按列使用 axis=0,按行使用 axis=1,一次处理整个表使用 axis=None

此方法对于将多个复杂逻辑应用于数据单元格非常强大。我们创建一个新的 DataFrame 来演示这一点。

[21]:
df2 = pd.DataFrame(
    np.random.default_rng(0).standard_normal((10, 4)), columns=["A", "B", "C", "D"]
)
df2.style
[21]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

例如,我们可以构建一个函数,当文本为负数时将其着色,然后将其与一个将忽略可忽略值单元格的函数链接起来。由于这会逐个查看每个元素,因此我们使用 map

[22]:
def style_negative(v, props=""):
    return props if v < 0 else None


s2 = df2.style.map(style_negative, props="color:red;").map(
    lambda v: "opacity: 20%;" if (v < 0.3) and (v > -0.3) else None
)
s2
[22]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

我们还可以构建一个函数来突出显示跨行、列和整个 DataFrame 的最大值。在这种情况下,我们使用 apply。下面我们突出显示列中的最大值。

[24]:
def highlight_max(s, props=""):
    return np.where(s == np.nanmax(s.values), props, "")


s2.apply(highlight_max, props="color:white;background-color:darkblue", axis=0)
[24]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

我们可以跨不同的轴使用相同的函数,此处以紫色突出显示 DataFrame 中的最大值,以粉色突出显示行最大值。

[26]:
s2.apply(highlight_max, props="color:white;background-color:pink;", axis=1).apply(
    highlight_max, props="color:white;background-color:purple", axis=None
)
[26]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

最后一个示例显示了某些样式如何被其他样式覆盖。通常,最后应用的样式是活动的,但您可以在 CSS 层次结构 部分了解更多信息。您还可以将这些样式应用于 DataFrame 的更精细部分 - 在 子集切片 部分了解更多信息。

使用类可以复制其中一些功能,但这可能更麻烦。请参阅 优化 中的第 3 项。

调试提示:如果您在编写样式函数时遇到问题,请尝试将其直接传递给 DataFrame.apply。内部,Styler.apply 使用 DataFrame.apply,因此结果应该相同,并且使用 DataFrame.apply,您将能够检查每个单元格中您打算使用的函数的 CSS 字符串输出。

作用于索引和列标题#

通过使用以下方法实现类似的应用程序,用于标题:

  • .map_index()(逐元素):接受一个接受单个值并返回 CSS 属性-值对字符串的函数。

  • .apply_index()(按级别):接受一个接受 Series 并返回 Series 或具有相同形状的 numpy 数组的函数,其中每个元素都是一个 CSS 属性-值对字符串。此方法一次传递您索引的每个级别。要设置索引样式,请使用 axis=0,要设置列标题样式,请使用 axis=1

您可以选择 MultiIndex 的一个 level,但目前这些方法不支持类似的 subset 应用。

[28]:
s2.map_index(lambda v: "color:pink;" if v > 4 else "color:darkblue;", axis=0)
s2.apply_index(
    lambda s: np.where(s.isin(["A", "B"]), "color:pink;", "color:darkblue;"), axis=1
)
[28]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

工具提示和标题#

可以使用 .set_caption() 方法添加表格标题。您可以使用表格样式来控制与标题相关的 CSS。

[29]:
s.set_caption(
    "Confusion matrix for multiple cancer prediction models."
).set_table_styles(
    [{"selector": "caption", "props": "caption-side: bottom; font-size:1.25em;"}],
    overwrite=False,
)
[29]:
用于多种癌症预测模型的混淆矩阵。
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

添加工具提示(自 1.3.0 版本起)可以使用 .set_tooltips() 方法完成,这与您通过提供具有相交索引和列的字符串 DataFrame 来为数据单元格添加 CSS 类的方式相同。您不必为工具提示指定 css_class 名称或任何 CSS props,因为有标准的默认值,但如果您想要更多的视觉控制,该选项是可用的。

[31]:
tt = pd.DataFrame(
    [
        [
            "This model has a very strong true positive rate",
            "This model's total number of false negatives is too high",
        ]
    ],
    index=["Tumour (Positive)"],
    columns=df.columns[[0, 3]],
)
s.set_tooltips(
    tt,
    props="visibility: hidden; position: absolute; z-index: 1; "
    "border: 1px solid #000066;"
    "background-color: white; color: #000066; font-size: 0.8em;"
    "transform: translate(0px, -24px); padding: 0.6em; "
    "border-radius: 0.5em;",
)
[31]:
用于多种癌症预测模型的混淆矩阵。
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

为我们的表格要做的最后一件事是添加高亮边框以引起观众对工具提示的注意。我们将像以前一样使用表格样式创建内部 CSS 类。设置类总是会覆盖,所以我们需要确保添加之前的类。

[33]:
s.set_table_styles(
    [  # create internal CSS classes
        {"selector": ".border-red", "props": "border: 2px dashed red;"},
        {"selector": ".border-green", "props": "border: 2px dashed green;"},
    ],
    overwrite=False,
)
cell_border = pd.DataFrame(
    [["border-green ", " ", " ", "border-red "], [" ", " ", " ", " "]],
    index=df.index,
    columns=df.columns[:4],
)
s.set_td_classes(cell_color + cell_border)
[33]:
用于多种癌症预测模型的混淆矩阵。
模型 决策树 回归
预测 肿瘤 非肿瘤 肿瘤 非肿瘤
实际标签        
肿瘤(阳性) 38 2 18 22
非肿瘤(阴性) 19 439 6 452

使用切片进行更精细控制#

我们到目前为止为 Styler.applyStyler.map 函数展示的示例并没有演示 subset 参数的使用。这是一个非常灵活的参数:它允许您将样式应用于特定的行或列,而无需将该逻辑编码到您的 style 函数中。

传递给 subset 的值与切片 DataFrame 的行为类似:

  • 标量被视为列标签

  • 列表(或 Series 或 NumPy 数组)被视为多个列标签

  • 元组被视为 (row_indexer, column_indexer)

可以考虑使用 pd.IndexSlice 来构造最后一个元组。我们将创建一个 MultiIndexed DataFrame 来演示该功能。

[35]:
df3 = pd.DataFrame(
    np.random.default_rng().standard_normal((4, 4)),
    pd.MultiIndex.from_product([["A", "B"], ["r1", "r2"]]),
    columns=["c1", "c2", "c3", "c4"],
)
df3
[35]:
c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

我们将使用子集将第三列和第四列中的最大值以红色文本突出显示。我们将子集切片区域以黄色突出显示。

[36]:
slice_ = ["c3", "c4"]
df3.style.apply(
    highlight_max, props="color:red;", axis=0, subset=slice_
).set_properties(**{"background-color": "#ffffb3"}, subset=slice_)
[36]:
    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

如果结合建议的 IndexSlice,则可以更灵活地跨两个维度进行索引。

[37]:
idx = pd.IndexSlice
slice_ = idx[idx[:, "r1"], idx["c2":"c4"]]
df3.style.apply(
    highlight_max, props="color:red;", axis=0, subset=slice_
).set_properties(**{"background-color": "#ffffb3"}, subset=slice_)
[37]:
    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

当与 axis=1 结合使用时,这还提供了对行进行子选择的灵活性。

[38]:
slice_ = idx[idx[:, "r2"], :]
df3.style.apply(
    highlight_max, props="color:red;", axis=1, subset=slice_
).set_properties(**{"background-color": "#ffffb3"}, subset=slice_)
[38]:
    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

还可以提供条件过滤

假设我们想在列 1 和列 3 的总和小于 -2.0 的情况下突出显示列 2 和列 4 中的最大值(本质上排除了行 (:,'r2')

[39]:
slice_ = idx[idx[(df3["c1"] + df3["c3"]) < -2.0], ["c2", "c4"]]
df3.style.apply(
    highlight_max, props="color:red;", axis=1, subset=slice_
).set_properties(**{"background-color": "#ffffb3"}, subset=slice_)
[39]:
    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

目前仅支持基于标签的切片,不支持基于位置的切片,也不支持可调用对象。

如果您的样式函数使用了 subsetaxis 关键字参数,请考虑将您的函数包装在 functools.partial 中,部分化该关键字。

my_func2 = functools.partial(my_func, subset=42)

优化#

通常,对于较小的表格和大多数情况,渲染的 HTML 不需要优化,我们也不太推荐这样做。有两种情况值得考虑:

  • 如果您正在渲染和样式化一个非常大的 HTML 表格,某些浏览器会出现性能问题。

  • 如果您使用 Styler 动态创建在线用户界面的部分内容,并希望提高网络性能。

在这里,我们建议采取以下步骤来实施:

1. 删除 UUID 和 cell_ids#

忽略 uuid 并将 cell_ids 设置为 False。这将防止不必要的 HTML。

这是次优的

[40]:
df4 = pd.DataFrame([[1, 2], [3, 4]])
s4 = df4.style

这样更好

[41]:
from pandas.io.formats.style import Styler

s4 = Styler(df4, uuid_len=0, cell_ids=False)

2. 使用表格样式#

尽可能使用表格样式(例如,一次性针对所有单元格、行或列),因为 CSS 几乎总是比其他格式更有效。

这是次优的

[42]:
props = 'font-family: "Times New Roman", Times, serif; color: #e83e8c; font-size:1.3em;'
df4.style.map(lambda x: props, subset=[1])
[42]:
  0 1
0 1 2
1 3 4

这样更好

[43]:
df4.style.set_table_styles([{"selector": "td.col1", "props": props}])
[43]:
  0 1
0 1 2
1 3 4

3. 设置类而不是使用 Styler 函数#

对于大型 DataFrame,当相同的样式应用于许多单元格时,将样式声明为类,然后将这些类应用于数据单元格,而不是直接将样式应用于单元格,可能会更有效。然而,当您不关心优化时,使用 Styler 函数 API 可能仍然更容易。

这是次优的

[44]:
df2.style.apply(
    highlight_max, props="color:white;background-color:darkblue;", axis=0
).apply(highlight_max, props="color:white;background-color:pink;", axis=1).apply(
    highlight_max, props="color:white;background-color:purple", axis=None
)
[44]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

这样更好

[45]:
build = lambda x: pd.DataFrame(x, index=df2.index, columns=df2.columns)
cls1 = build(df2.apply(highlight_max, props="cls-1 ", axis=0))
cls2 = build(
    df2.apply(highlight_max, props="cls-2 ", axis=1, result_type="expand").values
)
cls3 = build(highlight_max(df2, props="cls-3 "))
df2.style.set_table_styles(
    [
        {"selector": ".cls-1", "props": "color:white;background-color:darkblue;"},
        {"selector": ".cls-2", "props": "color:white;background-color:pink;"},
        {"selector": ".cls-3", "props": "color:white;background-color:purple;"},
    ]
).set_td_classes(cls1 + cls2 + cls3)
[45]:
  A B C D
0 0.125730 -0.132105 0.640423 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 1.042513
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

4. 不要使用工具提示#

工具提示需要 cell_ids 才能工作,并且它们会为每个数据单元格生成额外的 HTML 元素。

5. 如果每个字节都很重要,请使用字符串替换#

您可以替换默认的 CSS 字典来删除不必要的 HTML,或缩短默认的类名。您可以在 下方 了解更多关于 CSS 的信息。

[46]:
my_css = {
    "row_heading": "",
    "col_heading": "",
    "index_name": "",
    "col": "c",
    "row": "r",
    "col_trim": "",
    "row_trim": "",
    "level": "l",
    "data": "",
    "blank": "",
}
html = Styler(df4, uuid_len=0, cell_ids=False)
html.set_table_styles(
    [
        {"selector": "td", "props": props},
        {"selector": ".c1", "props": "color:green;"},
        {"selector": ".l0", "props": "color:blue;"},
    ],
    css_class_names=my_css,
)
print(html.to_html())
<style type="text/css">
#T_ td {
  font-family: "Times New Roman", Times, serif;
  color: #e83e8c;
  font-size: 1.3em;
}
#T_ .c1 {
  color: green;
}
#T_ .l0 {
  color: blue;
}
</style>
<table id="T_">
  <thead>
    <tr>
      <th class=" l0" >&nbsp;</th>
      <th class=" l0 c0" >0</th>
      <th class=" l0 c1" >1</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th class=" l0 r0" >0</th>
      <td class=" r0 c0" >1</td>
      <td class=" r0 c1" >2</td>
    </tr>
    <tr>
      <th class=" l0 r1" >1</th>
      <td class=" r1 c0" >3</td>
      <td class=" r1 c1" >4</td>
    </tr>
  </tbody>
</table>

[47]:
html
[47]:
  0 1
0 1 2
1 3 4

内置样式#

一些样式函数足够常见,我们已将其“内置”到 Styler 中,因此您无需自己编写和应用它们。当前此类函数的列表是:

每个函数的文档通常会提供更多关于其参数的示例。

突出显示空值#

[48]:
df2.iloc[0, 2] = np.nan
df2.iloc[4, 3] = np.nan
df2.loc[:4].style.highlight_null(color="yellow")
[48]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan

突出显示最小值或最大值#

[49]:
df2.loc[:4].style.highlight_max(
    axis=1, props=("color:white; font-weight:bold; background-color:darkblue;")
)
[49]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan

突出显示之间#

此方法接受浮点数范围,或匹配索引的 NumPy 数组或 Series。

[50]:
left = pd.Series([1.0, 0.0, 1.0], index=["A", "B", "D"])
df2.loc[:4].style.highlight_between(
    left=left, right=1.5, axis=1, props="color:white; background-color:purple;"
)
[50]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan

突出显示分位数#

用于检测最高或最低百分位数的值

[51]:
df2.loc[:4].style.highlight_quantile(q_left=0.85, axis=None, color="yellow")
[51]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan

背景渐变和文本渐变#

您可以使用 background_gradienttext_gradient 方法创建“热力图”。这些需要 matplotlib,我们将使用 Seaborn 来获取漂亮的颜色映射。

[52]:
import seaborn as sns

cm = sns.light_palette("green", as_cmap=True)

df2.style.background_gradient(cmap=cm)
[52]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431
[53]:
df2.style.text_gradient(cmap=cm)
[53]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

.background_gradient.text_gradient 具有许多关键字参数来定制渐变和颜色。请参阅文档。

设置属性#

当样式实际上不依赖于值时,请使用 Styler.set_properties。这只是 .map 的一个简单包装,其中函数为所有单元格返回相同的属性。

[54]:
df2.loc[:4].style.set_properties(
    **{"background-color": "black", "color": "lawngreen", "border-color": "white"}
)
[54]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan

条形图#

您可以在 DataFrame 中包含“条形图”。

[55]:
df2.style.bar(subset=["A", "B"], color="#d65f5f")
[55]:
  A B C D
0 0.125730 -0.132105 nan 0.104900
1 -0.535669 0.361595 1.304000 0.947081
2 -0.703735 -1.265421 -0.623274 0.041326
3 -2.325031 -0.218792 -1.245911 -0.732267
4 -0.544259 -0.316300 0.411631 nan
5 -0.128535 1.366463 -0.665195 0.351510
6 0.903470 0.094012 -0.743499 -0.921725
7 -0.457726 0.220195 -1.009618 -0.209176
8 -0.159225 0.540846 0.214659 0.355373
9 -0.653829 -0.129614 0.783975 1.493431

其他关键字参数可以提供对居中和定位的更多控制,您可以传递一个 [color_negative, color_positive] 列表来突出显示较低和较高的值,或者一个 matplotlib 颜色映射。

为了展示一个例子,这里是如何使用新的 align 选项改变上述内容,同时设置 vminvmax 限制、图形的 width,以及单元格的底层 CSS props,为显示文本和条形图留出空间。我们还使用 text_gradient 将文本的颜色设置为与条形图相同(使用 matplotlib 颜色映射)(尽管在这种情况下,没有这种额外效果的可视化可能更好)。

[56]:
df2.style.format("{:.3f}", na_rep="").bar(
    align=0,
    vmin=-2.5,
    vmax=2.5,
    cmap="bwr",
    height=50,
    width=60,
    props="width: 120px; border-right: 1px solid black;",
).text_gradient(cmap="bwr", vmin=-2.5, vmax=2.5)
[56]:
  A B C D
0 0.126 -0.132 0.105
1 -0.536 0.362 1.304 0.947
2 -0.704 -1.265 -0.623 0.041
3 -2.325 -0.219 -1.246 -0.732
4 -0.544 -0.316 0.412
5 -0.129 1.366 -0.665 0.352
6 0.903 0.094 -0.743 -0.922
7 -0.458 0.220 -1.010 -0.209
8 -0.159 0.541 0.215 0.355
9 -0.654 -0.130 0.784 1.493

以下示例旨在突出显示新对齐选项的行为

[58]:
HTML(head)
[58]:
对齐 全部负值 负值和正值 全部正值 大正值
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
中间
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
均值
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
99
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102

共享样式#

假设您为 DataFrame 构建了一个漂亮的样式,现在您想将相同的样式应用于第二个 DataFrame。使用 df1.style.export 导出样式,并在第二个 DataFrame 上使用 df1.style.set 导入它。

[59]:
style1 = (
    df2.style.map(style_negative, props="color:red;")
    .map(lambda v: "opacity: 20%;" if (v < 0.3) and (v > -0.3) else None)
    .set_table_styles([{"selector": "th", "props": "color: blue;"}])
    .hide(axis="index")
)
style1
[59]:
A B C D
0.125730 -0.132105 nan 0.104900
-0.535669 0.361595 1.304000 0.947081
-0.703735 -1.265421 -0.623274 0.041326
-2.325031 -0.218792 -1.245911 -0.732267
-0.544259 -0.316300 0.411631 nan
-0.128535 1.366463 -0.665195 0.351510
0.903470 0.094012 -0.743499 -0.921725
-0.457726 0.220195 -1.009618 -0.209176
-0.159225 0.540846 0.214659 0.355373
-0.653829 -0.129614 0.783975 1.493431
[60]:
style2 = df3.style
style2.use(style1.export())
style2
[60]:
c1 c2 c3 c4
0.295787 -2.213722 -1.695725 -1.409669
-1.532179 -0.167794 -0.142344 1.022587
0.253825 1.770438 0.631995 1.202775
-1.078887 -1.674201 -1.583150 0.487844

请注意,即使样式是数据感知的,您也能够共享它们。样式会在它们被used 的新 DataFrame 上重新评估。

限制#

  • 仅支持 DataFrame(使用 Series.to_frame().style

  • 索引和列不需要唯一,但某些样式函数只能与唯一的索引一起使用。

  • 没有大型表示,并且构造性能并不理想;尽管我们进行了一些 HTML 优化

  • 您只能应用样式,无法插入新的 HTML 实体,除非通过子类化。

其他有趣和有用的东西#

这里有一些有趣的例子。

小部件#

Styler 与小部件交互得很好。如果您是在线查看此内容而不是自己运行笔记本,那么您将错过交互式调整颜色主题的机会。

[61]:
from ipywidgets import widgets


@widgets.interact
def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0.0, 99.9), l_post=(0.0, 99.9)):
    return df2.style.background_gradient(
        cmap=sns.palettes.diverging_palette(
            h_neg=h_neg, h_pos=h_pos, s=s, l=l_post, as_cmap=True
        )
    )

放大#

[62]:
def magnify():
    return [
        {"selector": "th", "props": [("font-size", "4pt")]},
        {"selector": "td", "props": [("padding", "0em 0em")]},
        {"selector": "th:hover", "props": [("font-size", "12pt")]},
        {
            "selector": "tr:hover td:hover",
            "props": [("max-width", "200px"), ("font-size", "12pt")],
        },
    ]
[63]:
cmap = sns.diverging_palette(5, 250, as_cmap=True)
bigdf = pd.DataFrame(np.random.default_rng(25).standard_normal((20, 25))).cumsum()

bigdf.style.background_gradient(cmap, axis=1).set_properties(
    **{"max-width": "80px", "font-size": "1pt"}
).set_caption("Hover to magnify").format(precision=2).set_table_styles(magnify())
[63]:
悬停放大
  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
0 0.35 -0.00 -0.53 -2.28 0.02 0.93 1.04 -0.54 2.23 1.94 -0.23 -0.16 0.96 -0.25 0.22 1.22 1.19 -0.53 -0.46 -0.55 -0.01 0.07 -0.39 0.77 0.05
1 0.37 -1.97 -1.92 -2.97 0.38 0.06 2.60 -0.39 2.49 2.06 0.26 0.77 0.41 1.31 -0.55 1.74 0.98 -0.70 0.21 -0.35 1.59 -0.43 0.13 1.36 2.16
2 1.98 -1.27 -0.24 -2.12 -0.40 0.39 3.83 -0.91 4.01 2.42 -0.36 1.23 -1.16 0.62 -1.60 2.24 -0.04 -2.26 0.52 -0.83 0.87 -1.03 1.17 1.53 1.41
3 4.78 -0.78 1.67 -1.07 0.96 -0.48 3.26 -0.27 3.93 2.50 0.72 -1.07 -1.49 2.16 -2.07 2.28 0.34 -1.94 0.83 -1.76 1.20 -1.63 2.75 0.90 1.67
4 4.58 0.35 1.79 -0.36 0.40 -0.86 2.31 -0.44 3.65 1.36 -0.53 -0.91 -1.67 1.45 -2.99 1.17 0.44 -2.48 0.20 -2.32 0.73 -1.94 2.84 -0.86 1.41
5 3.38 -0.02 3.04 -2.28 -0.89 -1.38 0.01 1.95 3.01 2.98 -0.62 0.27 -0.86 1.15 -2.49 0.51 -0.04 -0.99 -0.67 -3.24 3.28 -2.33 3.14 0.78 0.92
6 2.81 1.80 3.02 -2.01 -1.23 -0.85 -1.57 2.12 4.01 3.94 -1.13 0.91 1.28 1.27 -1.81 0.15 -1.77 -0.25 -1.63 -3.94 3.34 -2.35 3.01 1.90 1.05
7 2.85 0.72 3.92 -3.29 -3.49 -1.67 -0.87 2.46 5.28 4.34 -0.76 1.24 0.64 0.81 -2.27 0.34 -2.71 -0.67 -1.35 -4.01 3.06 -2.55 1.78 0.54 0.25
8 3.80 1.51 4.19 -2.67 -2.71 -4.04 -1.42 3.30 7.04 4.52 0.96 2.40 0.78 -0.24 -3.28 0.28 -2.51 -0.74 -0.74 -3.44 3.11 -2.12 2.07 -1.35 -1.03
9 4.11 2.27 4.29 -2.97 -2.50 -3.58 -1.25 1.32 7.36 5.25 1.08 4.60 -0.64 -2.05 0.09 -0.72 -4.96 -1.31 0.09 -4.16 2.68 -1.37 4.02 -0.59 -0.72
10 3.67 3.02 7.08 -4.10 -3.57 -3.95 -0.53 1.94 7.14 4.78 2.44 5.06 0.69 -2.28 1.23 -1.56 -2.90 -1.71 -0.27 -3.72 2.50 -1.97 4.47 -1.23 1.21
11 2.98 3.85 6.33 -5.84 -5.90 -3.91 -1.94 2.08 6.33 4.70 2.41 6.84 0.50 -3.68 -1.10 -0.67 -2.80 -0.28 -1.88 -3.91 1.67 -1.48 4.15 0.17 0.79
12 2.76 3.21 6.80 -4.75 -5.36 -4.53 -3.00 1.17 6.52 4.20 2.25 7.97 0.98 -3.45 -1.59 -0.86 -3.09 -0.24 -2.08 -3.73 1.03 -0.18 4.54 0.48 1.69
13 1.69 2.02 5.31 -5.51 -4.79 -4.34 -1.42 -0.24 6.96 2.92 0.97 6.70 2.18 -3.38 -0.33 -0.77 -2.39 0.42 -1.53 -3.59 1.98 0.01 4.61 0.52 1.11
14 0.17 1.26 7.10 -5.35 -5.81 -4.61 -0.45 1.61 5.10 1.31 -1.18 6.09 1.25 -2.23 0.32 -1.33 -0.08 -0.19 -1.21 -2.83 0.97 0.13 4.89 0.36 1.83
15 0.01 0.61 7.94 -5.85 -5.35 -5.10 0.14 1.76 3.89 1.72 -1.61 7.86 0.71 -1.38 -1.95 -1.84 -1.88 -0.14 -2.02 -1.45 1.68 1.62 3.97 -1.88 1.80
16 1.42 0.91 9.86 -6.10 -6.02 -4.56 1.24 1.38 3.25 1.05 0.38 5.77 1.92 -1.51 -0.36 -1.01 -3.01 0.10 -2.50 -1.99 0.29 2.91 2.07 -1.64 3.87
17 1.94 2.55 10.78 -4.77 -6.87 -4.38 1.74 1.63 2.34 0.06 0.41 6.21 2.20 -3.13 -0.88 -1.57 -2.59 -0.76 -2.38 -3.21 -0.11 3.62 2.91 -2.87 3.98
18 1.27 4.45 11.25 -4.68 -4.93 -7.30 0.92 2.30 2.34 0.52 -0.15 6.01 2.52 -1.89 1.37 -2.65 -1.98 -2.85 -2.78 -2.81 -0.86 3.93 2.83 -1.04 4.17
19 0.72 2.89 10.94 -3.85 -2.50 -7.04 0.77 2.27 2.83 1.63 0.94 6.26 3.07 -1.99 2.65 -4.04 -0.91 -2.69 -2.70 -2.49 -0.86 3.16 2.88 -0.85 4.54

固定表头#

如果您在笔记本中显示一个大型矩阵或 DataFrame,但希望始终看到列和行标题,您可以使用 .set_sticky 方法,该方法会操作表格样式的 CSS。

[64]:
bigdf = pd.DataFrame(np.random.default_rng().standard_normal((16, 100)))
bigdf.style.set_sticky(axis="index")
[64]:
  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
0 1.644446 0.316389 1.822575 0.058249 0.272960 -0.992859 -1.406615 0.596833 -0.390452 -0.216308 -0.236805 0.011076 0.629521 -0.505489 0.449910 0.296012 0.907377 -1.791363 -0.443048 -0.018637 0.297168 -0.922488 -0.664267 1.635024 0.053085 -1.861741 -0.267765 1.152543 -0.735114 -0.840247 -1.281656 -0.305874 -0.780292 -0.742530 -0.144259 1.398880 0.233914 -0.116810 0.020009 0.631229 -0.740925 0.528057 3.082350 1.380913 -0.990916 -0.137182 1.276645 2.203624 -0.760137 -0.643519 -1.149958 1.445229 0.161453 -0.609732 -2.090247 -0.072868 -1.730071 0.322876 0.828713 0.172519 -0.254152 1.703894 -1.230651 1.168886 -0.743393 0.407562 -0.248417 -0.725939 1.484126 0.439564 -0.846774 -0.197091 -0.683574 1.837638 0.818560 0.134350 0.104483 0.110400 -1.807437 -1.470441 -0.172388 -0.686038 0.403531 0.326601 0.546593 0.845422 -0.216084 0.320535 -0.269461 1.103753 0.812585 -0.107018 -0.775563 1.210552 0.518237 0.595726 -0.361514 -0.189243 -1.082528 2.278431
1 -0.041866 -1.150698 -0.871130 -0.892388 0.219546 0.370028 -1.326786 1.251274 -0.292398 0.296830 0.307436 -0.359707 0.000239 -0.145901 2.730707 0.350292 -1.325557 -0.445053 0.901443 1.140967 -0.215859 -0.573830 -0.986761 -1.505207 0.803112 -0.492026 1.097916 -0.664498 -2.742163 -0.362009 -0.281563 0.223485 -1.825817 -0.162201 -0.713869 0.200137 1.099573 -0.479766 0.883267 1.319162 -0.999617 2.203245 0.187525 -0.603057 -0.868359 0.497418 -1.507363 1.184960 -0.605672 -1.184311 1.307592 1.463203 -1.367992 0.761049 0.173424 -1.805492 0.791097 -0.098776 -0.365125 0.174304 -0.363721 0.280235 0.767128 -0.592758 -3.496262 -0.958871 -0.426267 1.312785 0.054177 0.820841 1.629007 -0.531340 0.067092 -1.249489 -1.612646 -2.211713 -0.407212 -3.126022 -1.954622 -1.142636 -0.656593 0.780212 0.654562 0.847796 1.524720 0.995232 -0.126988 0.042045 -0.567728 -0.335551 -0.729098 1.371073 0.042106 1.107014 1.211240 1.048399 1.441789 0.453449 0.004651 -1.201286
2 0.982626 -0.162041 0.288834 0.743612 -2.691997 -0.285329 1.213255 1.700828 -0.325031 0.499129 1.803826 -1.123592 -0.372686 0.967336 1.697400 -0.743562 0.534235 0.469125 0.929446 -0.111087 -0.598359 -0.289278 -1.109232 1.037099 0.831092 2.190124 0.407548 -0.591373 -1.203340 0.334325 -1.268936 0.241257 0.990743 0.874077 -1.867397 0.702266 0.968566 -0.424235 0.591240 0.899166 0.748488 -0.033489 -1.785355 1.147753 1.365409 0.680179 0.184518 1.413968 0.491686 -0.793608 -0.568395 -0.148175 0.267424 0.732480 0.833680 -0.534657 0.610740 1.287655 -0.581902 -0.978567 -0.567395 0.238934 -1.658983 1.699655 0.349469 -0.629360 -0.320200 -2.667591 0.676364 -1.147084 -0.309491 -1.479214 -0.527351 -0.730012 0.125687 -0.002953 0.675185 -0.396889 -0.787309 -1.260459 -0.689626 -0.396777 0.793449 1.335890 0.402100 0.383154 0.239559 0.946700 2.633566 2.173507 -0.278412 -0.440502 0.310536 0.367111 -0.208590 -0.683383 -0.085675 -2.318822 -2.007481 1.963378
3 -0.174399 0.772998 0.349967 0.893162 -0.323689 0.024505 -1.787298 -1.537215 -1.265059 -0.794711 0.957017 0.616595 1.087908 -0.980637 -0.366200 -0.208228 -1.526557 -1.202464 -0.857895 0.474055 -0.036240 -0.169420 3.149457 -1.248729 0.648724 -1.201585 -0.416882 0.257153 -1.280088 -1.228204 -1.081947 -0.961326 -1.279582 -0.033799 1.635803 -0.236340 0.110607 -0.089784 -0.177481 -1.207262 0.844469 -2.446395 -0.016013 1.963714 -0.394486 0.007712 -0.231797 -0.003643 0.652228 -0.179861 -0.327667 1.517988 0.227823 -0.295946 0.710588 -0.269814 -0.252783 0.635090 0.731065 0.582337 0.586612 0.448222 1.528269 0.548486 -0.762893 1.855596 0.718824 -1.123796 -0.976386 1.227111 -0.584695 0.367847 -1.797194 0.987952 0.787809 -0.848248 0.710857 -0.821439 -0.789789 -0.355849 0.720215 0.382210 -0.438010 0.521886 0.254704 0.255897 0.829324 -0.267531 0.216955 -2.029004 0.795741 0.959946 1.977933 -0.038265 0.661490 -1.291257 0.480225 -0.815210 1.134917 0.230711
4 1.307274 -0.147261 -1.168273 -2.071692 -1.280001 -0.040172 -0.159808 0.836022 -0.855624 0.053404 -0.040143 -0.686116 1.430840 0.969792 1.337384 -1.732706 1.186756 1.505201 1.080427 1.054404 0.170759 -0.097667 -0.121594 -0.472254 0.339487 -0.813040 -1.855760 0.222074 1.860715 -1.454599 1.282065 0.920207 0.724235 0.919812 -0.378647 -0.111125 -1.797094 0.902818 -0.114896 0.569311 1.120045 0.429957 -0.570291 -1.929209 -0.110387 1.064316 0.580920 0.860093 2.189284 -0.467865 -0.229561 -0.231964 -0.758866 0.095398 1.949553 0.823495 -0.069294 1.185175 -0.489716 1.212726 1.364861 3.034572 -0.242182 -0.351040 -0.332186 1.047477 0.734342 -0.624267 2.280790 0.560223 1.033536 0.607561 0.479486 1.314072 -0.618344 -0.777133 -1.144214 2.375061 -0.867809 -0.012872 1.370926 2.801484 -1.821482 1.282187 -0.060528 -0.381011 0.093473 -1.400228 -1.179066 0.642866 0.373724 -1.945071 -0.031623 -1.268326 0.485358 -0.228175 -1.338185 -0.515345 -1.134390 0.350706
5 1.475494 -1.420144 -1.114249 0.139285 -0.567878 -0.354612 -0.270217 -0.182202 1.288483 -0.138849 -1.961259 0.652703 -1.044370 0.729025 -0.078419 0.559058 0.055319 -0.694454 -1.395079 -0.738723 1.013207 -1.863346 0.224460 -0.849350 -1.120836 0.506453 -0.548434 -0.806284 2.659026 -0.698576 0.539280 0.782162 0.158181 -1.529569 0.834952 1.073322 0.163351 0.811785 -0.546974 1.444224 0.718983 -0.428645 -0.683600 -0.329034 -1.249749 -0.511727 -0.346714 0.688423 1.054256 0.690683 2.276351 -1.194298 -0.750584 0.172980 0.014991 -0.845675 1.112302 -0.906177 -1.554281 -1.137636 -0.321966 -1.176904 -0.200448 0.500272 0.248168 -0.323774 -0.980287 0.517695 -1.793398 -0.732176 -0.345382 0.431567 2.177516 1.573274 0.337083 -2.197812 0.644255 -1.773536 -1.061013 0.323582 0.933226 0.285079 0.951401 -1.977635 -1.108542 -0.856453 1.227314 -1.400090 -0.919909 0.187602 -0.596913 -0.412432 -1.494708 1.373662 0.097690 2.055733 0.011200 -0.566628 0.097283 0.157233
6 1.245830 -1.600315 0.316923 2.028456 -1.543372 -0.133891 -1.899870 -0.494004 -0.788653 0.846073 1.053881 -0.835824 -0.302716 -1.095685 0.525533 -1.425552 -1.422198 0.540288 -1.274927 2.596897 0.327870 0.585448 0.249197 -0.355780 0.322848 -1.650182 -0.550181 -1.335715 -0.450820 -0.662436 -0.839484 -0.471767 0.031991 1.107493 1.028724 0.111348 0.706302 -1.794661 0.092440 -0.300298 -1.070448 -1.039569 -1.018395 -0.240576 0.139633 0.611957 -0.819060 1.331881 0.009422 0.745530 0.062289 0.367981 -0.758342 0.352606 -0.365754 1.066353 -1.355196 -0.454803 0.598824 1.342442 -2.461906 -2.555299 -0.767342 -0.558897 0.808228 -1.653101 -0.836969 -1.679822 0.315784 0.436735 0.474111 -0.368929 -1.299504 1.987583 1.366028 -0.869646 0.723343 -1.175973 0.473442 -1.053522 -1.531158 -0.539538 -1.087674 -0.657522 -0.458283 -1.921458 0.368039 -0.215086 0.262871 -1.424903 0.862992 -0.740545 -0.479166 0.293551 -0.794890 0.125389 0.456655 -1.334549 -1.086340 -0.481435
7 -0.666627 -0.391587 -0.129154 0.322812 -0.187689 0.515694 -0.765581 -1.272560 -0.074839 1.327164 -0.642819 -1.139299 -1.413036 2.225186 0.175772 -1.797966 -0.037341 -1.055676 -1.089543 0.288420 -0.745087 -0.203264 0.033613 -0.493804 0.512476 -0.546505 0.815360 -0.755975 -0.310782 0.983578 -0.953500 -2.161508 0.130728 -1.163023 0.977181 -2.223435 -0.047557 0.203607 0.659665 -0.872126 1.392115 1.252733 -0.598547 0.827871 0.870218 -1.040962 -0.591821 0.185070 0.697530 -0.502390 -1.364248 1.217342 -1.123903 0.380739 -0.302991 0.426186 -0.371364 -2.535894 0.452562 -0.812664 0.787695 -1.843102 -0.152859 0.324664 -1.105414 1.107938 -2.311112 1.480997 -0.528401 -1.484068 0.283346 1.632304 -0.432395 -0.429100 -0.911396 -1.115844 -1.714466 2.359956 2.733418 0.266747 0.120346 -0.446718 -0.070777 -1.517549 0.101852 -0.823845 2.170714 -0.759554 1.950104 0.092761 1.235554 -1.063000 0.078999 0.076283 1.015173 0.838430 -0.589670 -0.471805 -0.411913 1.027948
8 -1.120145 0.079367 -1.460129 0.796803 1.186269 -1.722091 1.343569 -1.099058 -0.745066 1.386027 -0.557277 0.682646 -0.389677 1.022520 -1.904255 0.057242 -0.631464 1.060537 -3.713088 0.211778 -0.032890 1.208927 -0.224855 -0.381166 0.583184 -0.400829 1.220067 0.106988 0.411628 2.006558 -0.165597 -0.254252 0.355495 1.581721 -0.531915 1.107554 -0.262332 -0.952369 -0.430627 1.783336 2.102952 1.013398 -1.035249 0.344105 0.419060 -0.515409 -1.601572 1.426035 0.958222 0.949601 0.072460 -1.150490 0.758652 -0.965956 1.025279 0.173889 1.482953 0.648826 -0.593986 0.289693 0.106806 0.878338 -0.727842 0.202902 -0.666308 -0.360165 -0.212048 1.828206 -0.793867 0.631551 0.783171 -1.951037 -1.596158 -1.165412 -0.019613 0.363675 -0.609028 1.121255 -0.633024 0.383733 -0.071099 0.905810 -0.746383 -0.106705 0.574281 0.076073 1.112516 -1.486673 0.933428 1.136527 0.654915 2.079827 -0.249178 0.266707 -0.293233 0.204544 -0.750035 -1.316983 0.380331 0.511996
9 2.473246 -0.875644 1.043054 -0.178877 -0.755217 -1.787174 0.003384 -0.640753 -0.415939 -0.962653 -0.985272 -0.151625 -0.361220 -0.421538 1.698237 1.239084 1.208072 -0.113157 0.215352 1.972413 0.733303 -2.417300 1.362046 1.792873 0.771237 1.117970 1.006447 -0.638750 -0.927349 -0.102418 1.676281 -0.048318 0.640166 1.088523 -0.893051 0.891439 1.052201 -0.766509 -0.115570 -0.887299 -0.071576 1.449380 0.523628 -0.369116 -0.072966 1.482640 0.696838 0.050366 1.758962 -0.302001 0.415237 0.352729 1.247878 -0.741262 -0.298219 0.510795 0.075519 0.818694 -1.236537 -0.163264 0.229487 1.013874 0.087919 -0.738962 2.286609 1.777323 -0.786276 0.390833 0.079690 0.995578 -0.123031 0.242833 -0.781300 -0.944531 -1.307105 0.634402 -1.196089 -0.366814 0.509353 0.650519 -0.471010 0.080152 -1.511010 0.695639 0.429393 -0.713210 0.660811 1.032903 -1.073719 -1.565745 -0.505353 0.014718 1.000641 0.453843 -0.861089 -1.385547 -0.360502 -0.309470 -0.964340 -0.176677
10 1.215158 0.783979 0.372376 1.089963 -0.759181 0.955893 0.061013 2.526342 -0.568802 0.399785 -1.232773 -0.431258 -0.187670 0.142237 2.229015 -0.949857 -0.837181 0.186915 -1.573448 -0.443802 -2.078479 0.345695 0.036546 1.338971 0.812287 0.082781 0.597771 1.156034 -1.382762 0.032500 -0.371491 -0.222128 -1.758367 -0.916259 0.705719 -1.467374 -1.321395 -1.632817 -2.487807 0.145645 -0.215974 0.401696 -0.109110 2.623708 0.329630 -0.416048 -0.552243 -0.325580 0.731877 1.418553 0.402234 2.510738 2.232637 -0.253628 -1.290301 0.293129 -0.209060 0.882067 0.540456 -0.445221 -0.962856 -0.711012 0.334096 0.410932 2.158462 -1.216937 -0.618347 0.086243 0.258014 0.621977 -0.090952 -0.504986 -0.543687 -1.404561 -0.737265 -0.304459 0.286345 1.026951 0.747515 -2.056777 0.076334 1.492592 0.311670 0.413515 -0.389321 -1.836326 0.688201 1.441546 -1.914056 -0.536475 -0.773196 -0.821108 0.358993 0.329763 0.653118 -1.789946 0.093994 1.422007 -0.530495 1.433546
11 -0.383178 -1.293075 2.232080 1.008208 0.690823 -0.265701 0.895858 0.868161 -0.585569 -0.029640 0.358899 -2.272106 0.689153 -0.383252 -0.280169 -1.051004 -1.355970 -1.540744 0.407955 0.690407 -0.324348 -0.515580 0.036701 -0.492272 -0.393917 0.964351 -0.875240 -1.692645 -0.845578 -0.919375 1.515881 -0.914460 0.845607 -0.920968 1.688416 1.810720 -0.911477 -1.398060 -0.343449 -0.996007 1.099394 0.548631 1.411551 0.791754 0.660730 0.636439 -0.902702 1.729570 0.705220 0.984945 0.344469 0.645971 -1.270632 -0.828542 0.261362 1.101084 0.016608 0.766482 1.014087 -0.199839 -0.370854 0.265364 0.464564 0.520593 0.428554 0.583909 1.763114 -0.256941 0.362013 -1.773812 -1.532465 -1.029538 -0.687087 -0.134767 1.327257 -0.790544 -0.543572 0.348118 -0.361243 -0.838300 -0.980450 -0.029829 -0.717558 0.862414 0.314404 2.163535 -1.966349 -0.247445 0.197090 -1.533577 -1.624240 0.607302 3.392405 -1.506540 -0.352565 0.484623 -1.168758 0.200015 -0.350147 -0.283178
12 -1.215405 1.577351 -0.185874 -1.141476 0.457267 1.685075 1.077628 -0.231406 1.110184 -1.105144 -0.528167 1.178595 -0.204829 0.369673 1.350309 0.669154 2.002141 -0.188777 0.489174 -0.564570 0.262250 0.926505 0.511230 0.949313 0.053847 -1.682508 0.398444 -1.046470 1.716457 -0.659703 -0.840734 2.333336 -1.377479 -1.149077 -0.733111 0.366767 0.335292 -1.382667 -0.794672 0.313059 0.827463 -1.610093 0.528185 -0.167029 1.254968 -1.452055 -0.628225 -0.414733 -0.470607 2.107992 -0.213162 1.256675 -0.566967 -0.670965 -0.549343 -0.611266 0.288009 0.132394 0.358884 0.436466 0.665781 -0.081569 -0.021983 1.310930 -0.359526 0.260452 0.268138 1.723058 0.569677 -0.181663 -1.729383 -0.766575 -1.328451 0.012948 -0.502039 1.976053 0.454888 1.323948 -1.097333 -0.768619 1.320548 0.233246 -0.083031 -1.931873 2.189127 -0.051524 -1.647792 -0.728172 0.200191 -0.102758 0.460571 0.054086 -1.333049 1.564177 1.520115 1.532357 -0.521081 -1.037463 -0.413432 1.118277
13 0.213077 -1.061085 -0.997473 -1.446055 -0.024562 0.120896 -0.461501 -1.138477 0.983769 -0.140340 -0.302253 -0.540140 0.793527 0.011669 0.226834 -1.867136 -0.954558 -1.274738 -0.462769 -0.262035 -1.048895 -0.934456 0.617085 -1.197115 0.056404 1.499859 0.547669 2.797501 -0.625559 -0.248493 -0.453503 -0.836448 -1.779570 0.183616 0.102128 -1.385078 -0.585159 -0.112047 -0.303744 -0.213145 2.354225 0.598409 -2.154033 -1.973791 0.374794 0.577364 1.129823 -0.191984 0.377221 -0.233501 2.474922 -0.006907 -0.065430 0.965006 0.304154 0.533525 0.411437 -1.177894 0.611097 0.567003 0.988151 -0.638314 0.165525 -1.342050 -0.023097 1.631808 0.676776 -1.313850 -1.118955 1.015523 -0.433199 -0.524551 -0.274260 -0.301467 -0.890276 -1.546782 -0.246803 0.870468 1.689140 -0.803555 -0.800506 -0.053966 -1.538075 -0.874835 0.635541 -0.976896 0.904032 -0.418837 1.019360 0.120392 0.074966 0.599137 -0.716341 1.244792 1.453692 0.728159 0.481655 -0.064549 -0.381611 1.278603
14 1.470791 0.593878 0.836668 0.460491 1.042540 0.183481 -0.661539 0.115304 2.031085 1.242436 0.259781 -0.256159 -0.206609 -0.528230 -1.872724 1.588268 1.685884 0.018064 -2.079512 -1.543943 -0.148221 -0.272267 -1.278324 -0.442309 1.471981 1.018180 -0.337670 -0.573119 -0.139676 -0.497598 -1.020594 1.266699 2.295973 -0.716763 -0.311295 0.110729 0.610885 -0.484625 -0.939302 -1.236912 -0.509133 1.943533 1.367610 -1.490607 0.063574 -1.032744 -0.726389 -0.842815 -1.121529 0.171243 1.630980 -1.867818 0.351191 -1.275543 -1.545503 0.105977 2.001098 -1.247518 -0.345204 -0.462490 0.045033 0.198252 0.435874 0.751281 -0.483369 -0.883749 -0.706197 -1.346183 0.707285 0.130326 1.448559 -0.685684 0.152063 -0.958964 0.599144 -0.498841 -0.255264 -1.106058 0.056245 -1.865467 1.213610 -1.113450 -0.321455 0.460922 -1.322547 1.424683 2.218220 1.182406 -0.442274 1.862596 0.516616 0.540556 -1.486680 0.299545 -0.052014 -0.545246 -2.298098 -0.879502 -0.987752 0.372231
15 -0.121190 0.028235 0.229005 -1.772444 0.523793 1.313733 1.495456 -0.203124 -0.086773 -0.909066 0.084165 -0.768907 -1.054366 0.775486 -2.504936 1.924625 -0.909086 0.825028 2.387538 1.828123 0.115242 -0.326753 -1.404164 0.363681 -0.306493 1.905121 0.312672 -0.157399 -0.456277 0.206394 2.739692 1.334705 0.968743 -0.553691 -1.522574 1.322188 0.210698 -0.320464 0.912169 0.721823 0.472072 -0.801196 -1.041426 -0.561613 0.222571 0.527403 0.050054 1.618758 -0.415361 -0.500430 0.437452 0.575047 -0.228483 1.003212 0.215165 1.214890 0.939075 -0.335936 -1.669834 1.275661 -0.428725 -2.671502 -2.120515 -0.766720 -0.257375 0.350390 1.413539 -0.472909 -0.433935 -0.422629 0.367910 -1.466262 0.602139 2.266931 -0.162298 1.173774 -1.964278 0.582046 0.219679 -1.264104 -0.698571 -1.997247 0.831479 -1.377618 0.383037 0.282994 0.404398 -0.159537 1.508055 -1.592587 1.546873 -0.235228 1.451674 0.364401 0.213713 -1.878235 -1.089183 1.194839 0.055609 1.007122

也可以固定 MultiIndexes,甚至只固定特定的级别。

[65]:
bigdf.index = pd.MultiIndex.from_product([["A", "B"], [0, 1], [0, 1, 2, 3]])
bigdf.style.set_sticky(axis="index", pixel_size=18, levels=[1, 2])
[65]:
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
A 0 0 1.644446 0.316389 1.822575 0.058249 0.272960 -0.992859 -1.406615 0.596833 -0.390452 -0.216308 -0.236805 0.011076 0.629521 -0.505489 0.449910 0.296012 0.907377 -1.791363 -0.443048 -0.018637 0.297168 -0.922488 -0.664267 1.635024 0.053085 -1.861741 -0.267765 1.152543 -0.735114 -0.840247 -1.281656 -0.305874 -0.780292 -0.742530 -0.144259 1.398880 0.233914 -0.116810 0.020009 0.631229 -0.740925 0.528057 3.082350 1.380913 -0.990916 -0.137182 1.276645 2.203624 -0.760137 -0.643519 -1.149958 1.445229 0.161453 -0.609732 -2.090247 -0.072868 -1.730071 0.322876 0.828713 0.172519 -0.254152 1.703894 -1.230651 1.168886 -0.743393 0.407562 -0.248417 -0.725939 1.484126 0.439564 -0.846774 -0.197091 -0.683574 1.837638 0.818560 0.134350 0.104483 0.110400 -1.807437 -1.470441 -0.172388 -0.686038 0.403531 0.326601 0.546593 0.845422 -0.216084 0.320535 -0.269461 1.103753 0.812585 -0.107018 -0.775563 1.210552 0.518237 0.595726 -0.361514 -0.189243 -1.082528 2.278431
1 -0.041866 -1.150698 -0.871130 -0.892388 0.219546 0.370028 -1.326786 1.251274 -0.292398 0.296830 0.307436 -0.359707 0.000239 -0.145901 2.730707 0.350292 -1.325557 -0.445053 0.901443 1.140967 -0.215859 -0.573830 -0.986761 -1.505207 0.803112 -0.492026 1.097916 -0.664498 -2.742163 -0.362009 -0.281563 0.223485 -1.825817 -0.162201 -0.713869 0.200137 1.099573 -0.479766 0.883267 1.319162 -0.999617 2.203245 0.187525 -0.603057 -0.868359 0.497418 -1.507363 1.184960 -0.605672 -1.184311 1.307592 1.463203 -1.367992 0.761049 0.173424 -1.805492 0.791097 -0.098776 -0.365125 0.174304 -0.363721 0.280235 0.767128 -0.592758 -3.496262 -0.958871 -0.426267 1.312785 0.054177 0.820841 1.629007 -0.531340 0.067092 -1.249489 -1.612646 -2.211713 -0.407212 -3.126022 -1.954622 -1.142636 -0.656593 0.780212 0.654562 0.847796 1.524720 0.995232 -0.126988 0.042045 -0.567728 -0.335551 -0.729098 1.371073 0.042106 1.107014 1.211240 1.048399 1.441789 0.453449 0.004651 -1.201286
2 0.982626 -0.162041 0.288834 0.743612 -2.691997 -0.285329 1.213255 1.700828 -0.325031 0.499129 1.803826 -1.123592 -0.372686 0.967336 1.697400 -0.743562 0.534235 0.469125 0.929446 -0.111087 -0.598359 -0.289278 -1.109232 1.037099 0.831092 2.190124 0.407548 -0.591373 -1.203340 0.334325 -1.268936 0.241257 0.990743 0.874077 -1.867397 0.702266 0.968566 -0.424235 0.591240 0.899166 0.748488 -0.033489 -1.785355 1.147753 1.365409 0.680179 0.184518 1.413968 0.491686 -0.793608 -0.568395 -0.148175 0.267424 0.732480 0.833680 -0.534657 0.610740 1.287655 -0.581902 -0.978567 -0.567395 0.238934 -1.658983 1.699655 0.349469 -0.629360 -0.320200 -2.667591 0.676364 -1.147084 -0.309491 -1.479214 -0.527351 -0.730012 0.125687 -0.002953 0.675185 -0.396889 -0.787309 -1.260459 -0.689626 -0.396777 0.793449 1.335890 0.402100 0.383154 0.239559 0.946700 2.633566 2.173507 -0.278412 -0.440502 0.310536 0.367111 -0.208590 -0.683383 -0.085675 -2.318822 -2.007481 1.963378
3 -0.174399 0.772998 0.349967 0.893162 -0.323689 0.024505 -1.787298 -1.537215 -1.265059 -0.794711 0.957017 0.616595 1.087908 -0.980637 -0.366200 -0.208228 -1.526557 -1.202464 -0.857895 0.474055 -0.036240 -0.169420 3.149457 -1.248729 0.648724 -1.201585 -0.416882 0.257153 -1.280088 -1.228204 -1.081947 -0.961326 -1.279582 -0.033799 1.635803 -0.236340 0.110607 -0.089784 -0.177481 -1.207262 0.844469 -2.446395 -0.016013 1.963714 -0.394486 0.007712 -0.231797 -0.003643 0.652228 -0.179861 -0.327667 1.517988 0.227823 -0.295946 0.710588 -0.269814 -0.252783 0.635090 0.731065 0.582337 0.586612 0.448222 1.528269 0.548486 -0.762893 1.855596 0.718824 -1.123796 -0.976386 1.227111 -0.584695 0.367847 -1.797194 0.987952 0.787809 -0.848248 0.710857 -0.821439 -0.789789 -0.355849 0.720215 0.382210 -0.438010 0.521886 0.254704 0.255897 0.829324 -0.267531 0.216955 -2.029004 0.795741 0.959946 1.977933 -0.038265 0.661490 -1.291257 0.480225 -0.815210 1.134917 0.230711
1 0 1.307274 -0.147261 -1.168273 -2.071692 -1.280001 -0.040172 -0.159808 0.836022 -0.855624 0.053404 -0.040143 -0.686116 1.430840 0.969792 1.337384 -1.732706 1.186756 1.505201 1.080427 1.054404 0.170759 -0.097667 -0.121594 -0.472254 0.339487 -0.813040 -1.855760 0.222074 1.860715 -1.454599 1.282065 0.920207 0.724235 0.919812 -0.378647 -0.111125 -1.797094 0.902818 -0.114896 0.569311 1.120045 0.429957 -0.570291 -1.929209 -0.110387 1.064316 0.580920 0.860093 2.189284 -0.467865 -0.229561 -0.231964 -0.758866 0.095398 1.949553 0.823495 -0.069294 1.185175 -0.489716 1.212726 1.364861 3.034572 -0.242182 -0.351040 -0.332186 1.047477 0.734342 -0.624267 2.280790 0.560223 1.033536 0.607561 0.479486 1.314072 -0.618344 -0.777133 -1.144214 2.375061 -0.867809 -0.012872 1.370926 2.801484 -1.821482 1.282187 -0.060528 -0.381011 0.093473 -1.400228 -1.179066 0.642866 0.373724 -1.945071 -0.031623 -1.268326 0.485358 -0.228175 -1.338185 -0.515345 -1.134390 0.350706
1 1.475494 -1.420144 -1.114249 0.139285 -0.567878 -0.354612 -0.270217 -0.182202 1.288483 -0.138849 -1.961259 0.652703 -1.044370 0.729025 -0.078419 0.559058 0.055319 -0.694454 -1.395079 -0.738723 1.013207 -1.863346 0.224460 -0.849350 -1.120836 0.506453 -0.548434 -0.806284 2.659026 -0.698576 0.539280 0.782162 0.158181 -1.529569 0.834952 1.073322 0.163351 0.811785 -0.546974 1.444224 0.718983 -0.428645 -0.683600 -0.329034 -1.249749 -0.511727 -0.346714 0.688423 1.054256 0.690683 2.276351 -1.194298 -0.750584 0.172980 0.014991 -0.845675 1.112302 -0.906177 -1.554281 -1.137636 -0.321966 -1.176904 -0.200448 0.500272 0.248168 -0.323774 -0.980287 0.517695 -1.793398 -0.732176 -0.345382 0.431567 2.177516 1.573274 0.337083 -2.197812 0.644255 -1.773536 -1.061013 0.323582 0.933226 0.285079 0.951401 -1.977635 -1.108542 -0.856453 1.227314 -1.400090 -0.919909 0.187602 -0.596913 -0.412432 -1.494708 1.373662 0.097690 2.055733 0.011200 -0.566628 0.097283 0.157233
2 1.245830 -1.600315 0.316923 2.028456 -1.543372 -0.133891 -1.899870 -0.494004 -0.788653 0.846073 1.053881 -0.835824 -0.302716 -1.095685 0.525533 -1.425552 -1.422198 0.540288 -1.274927 2.596897 0.327870 0.585448 0.249197 -0.355780 0.322848 -1.650182 -0.550181 -1.335715 -0.450820 -0.662436 -0.839484 -0.471767 0.031991 1.107493 1.028724 0.111348 0.706302 -1.794661 0.092440 -0.300298 -1.070448 -1.039569 -1.018395 -0.240576 0.139633 0.611957 -0.819060 1.331881 0.009422 0.745530 0.062289 0.367981 -0.758342 0.352606 -0.365754 1.066353 -1.355196 -0.454803 0.598824 1.342442 -2.461906 -2.555299 -0.767342 -0.558897 0.808228 -1.653101 -0.836969 -1.679822 0.315784 0.436735 0.474111 -0.368929 -1.299504 1.987583 1.366028 -0.869646 0.723343 -1.175973 0.473442 -1.053522 -1.531158 -0.539538 -1.087674 -0.657522 -0.458283 -1.921458 0.368039 -0.215086 0.262871 -1.424903 0.862992 -0.740545 -0.479166 0.293551 -0.794890 0.125389 0.456655 -1.334549 -1.086340 -0.481435
3 -0.666627 -0.391587 -0.129154 0.322812 -0.187689 0.515694 -0.765581 -1.272560 -0.074839 1.327164 -0.642819 -1.139299 -1.413036 2.225186 0.175772 -1.797966 -0.037341 -1.055676 -1.089543 0.288420 -0.745087 -0.203264 0.033613 -0.493804 0.512476 -0.546505 0.815360 -0.755975 -0.310782 0.983578 -0.953500 -2.161508 0.130728 -1.163023 0.977181 -2.223435 -0.047557 0.203607 0.659665 -0.872126 1.392115 1.252733 -0.598547 0.827871 0.870218 -1.040962 -0.591821 0.185070 0.697530 -0.502390 -1.364248 1.217342 -1.123903 0.380739 -0.302991 0.426186 -0.371364 -2.535894 0.452562 -0.812664 0.787695 -1.843102 -0.152859 0.324664 -1.105414 1.107938 -2.311112 1.480997 -0.528401 -1.484068 0.283346 1.632304 -0.432395 -0.429100 -0.911396 -1.115844 -1.714466 2.359956 2.733418 0.266747 0.120346 -0.446718 -0.070777 -1.517549 0.101852 -0.823845 2.170714 -0.759554 1.950104 0.092761 1.235554 -1.063000 0.078999 0.076283 1.015173 0.838430 -0.589670 -0.471805 -0.411913 1.027948
B 0 0 -1.120145 0.079367 -1.460129 0.796803 1.186269 -1.722091 1.343569 -1.099058 -0.745066 1.386027 -0.557277 0.682646 -0.389677 1.022520 -1.904255 0.057242 -0.631464 1.060537 -3.713088 0.211778 -0.032890 1.208927 -0.224855 -0.381166 0.583184 -0.400829 1.220067 0.106988 0.411628 2.006558 -0.165597 -0.254252 0.355495 1.581721 -0.531915 1.107554 -0.262332 -0.952369 -0.430627 1.783336 2.102952 1.013398 -1.035249 0.344105 0.419060 -0.515409 -1.601572 1.426035 0.958222 0.949601 0.072460 -1.150490 0.758652 -0.965956 1.025279 0.173889 1.482953 0.648826 -0.593986 0.289693 0.106806 0.878338 -0.727842 0.202902 -0.666308 -0.360165 -0.212048 1.828206 -0.793867 0.631551 0.783171 -1.951037 -1.596158 -1.165412 -0.019613 0.363675 -0.609028 1.121255 -0.633024 0.383733 -0.071099 0.905810 -0.746383 -0.106705 0.574281 0.076073 1.112516 -1.486673 0.933428 1.136527 0.654915 2.079827 -0.249178 0.266707 -0.293233 0.204544 -0.750035 -1.316983 0.380331 0.511996
1 2.473246 -0.875644 1.043054 -0.178877 -0.755217 -1.787174 0.003384 -0.640753 -0.415939 -0.962653 -0.985272 -0.151625 -0.361220 -0.421538 1.698237 1.239084 1.208072 -0.113157 0.215352 1.972413 0.733303 -2.417300 1.362046 1.792873 0.771237 1.117970 1.006447 -0.638750 -0.927349 -0.102418 1.676281 -0.048318 0.640166 1.088523 -0.893051 0.891439 1.052201 -0.766509 -0.115570 -0.887299 -0.071576 1.449380 0.523628 -0.369116 -0.072966 1.482640 0.696838 0.050366 1.758962 -0.302001 0.415237 0.352729 1.247878 -0.741262 -0.298219 0.510795 0.075519 0.818694 -1.236537 -0.163264 0.229487 1.013874 0.087919 -0.738962 2.286609 1.777323 -0.786276 0.390833 0.079690 0.995578 -0.123031 0.242833 -0.781300 -0.944531 -1.307105 0.634402 -1.196089 -0.366814 0.509353 0.650519 -0.471010 0.080152 -1.511010 0.695639 0.429393 -0.713210 0.660811 1.032903 -1.073719 -1.565745 -0.505353 0.014718 1.000641 0.453843 -0.861089 -1.385547 -0.360502 -0.309470 -0.964340 -0.176677
2 1.215158 0.783979 0.372376 1.089963 -0.759181 0.955893 0.061013 2.526342 -0.568802 0.399785 -1.232773 -0.431258 -0.187670 0.142237 2.229015 -0.949857 -0.837181 0.186915 -1.573448 -0.443802 -2.078479 0.345695 0.036546 1.338971 0.812287 0.082781 0.597771 1.156034 -1.382762 0.032500 -0.371491 -0.222128 -1.758367 -0.916259 0.705719 -1.467374 -1.321395 -1.632817 -2.487807 0.145645 -0.215974 0.401696 -0.109110 2.623708 0.329630 -0.416048 -0.552243 -0.325580 0.731877 1.418553 0.402234 2.510738 2.232637 -0.253628 -1.290301 0.293129 -0.209060 0.882067 0.540456 -0.445221 -0.962856 -0.711012 0.334096 0.410932 2.158462 -1.216937 -0.618347 0.086243 0.258014 0.621977 -0.090952 -0.504986 -0.543687 -1.404561 -0.737265 -0.304459 0.286345 1.026951 0.747515 -2.056777 0.076334 1.492592 0.311670 0.413515 -0.389321 -1.836326 0.688201 1.441546 -1.914056 -0.536475 -0.773196 -0.821108 0.358993 0.329763 0.653118 -1.789946 0.093994 1.422007 -0.530495 1.433546
3 -0.383178 -1.293075 2.232080 1.008208 0.690823 -0.265701 0.895858 0.868161 -0.585569 -0.029640 0.358899 -2.272106 0.689153 -0.383252 -0.280169 -1.051004 -1.355970 -1.540744 0.407955 0.690407 -0.324348 -0.515580 0.036701 -0.492272 -0.393917 0.964351 -0.875240 -1.692645 -0.845578 -0.919375 1.515881 -0.914460 0.845607 -0.920968 1.688416 1.810720 -0.911477 -1.398060 -0.343449 -0.996007 1.099394 0.548631 1.411551 0.791754 0.660730 0.636439 -0.902702 1.729570 0.705220 0.984945 0.344469 0.645971 -1.270632 -0.828542 0.261362 1.101084 0.016608 0.766482 1.014087 -0.199839 -0.370854 0.265364 0.464564 0.520593 0.428554 0.583909 1.763114 -0.256941 0.362013 -1.773812 -1.532465 -1.029538 -0.687087 -0.134767 1.327257 -0.790544 -0.543572 0.348118 -0.361243 -0.838300 -0.980450 -0.029829 -0.717558 0.862414 0.314404 2.163535 -1.966349 -0.247445 0.197090 -1.533577 -1.624240 0.607302 3.392405 -1.506540 -0.352565 0.484623 -1.168758 0.200015 -0.350147 -0.283178
1 0 -1.215405 1.577351 -0.185874 -1.141476 0.457267 1.685075 1.077628 -0.231406 1.110184 -1.105144 -0.528167 1.178595 -0.204829 0.369673 1.350309 0.669154 2.002141 -0.188777 0.489174 -0.564570 0.262250 0.926505 0.511230 0.949313 0.053847 -1.682508 0.398444 -1.046470 1.716457 -0.659703 -0.840734 2.333336 -1.377479 -1.149077 -0.733111 0.366767 0.335292 -1.382667 -0.794672 0.313059 0.827463 -1.610093 0.528185 -0.167029 1.254968 -1.452055 -0.628225 -0.414733 -0.470607 2.107992 -0.213162 1.256675 -0.566967 -0.670965 -0.549343 -0.611266 0.288009 0.132394 0.358884 0.436466 0.665781 -0.081569 -0.021983 1.310930 -0.359526 0.260452 0.268138 1.723058 0.569677 -0.181663 -1.729383 -0.766575 -1.328451 0.012948 -0.502039 1.976053 0.454888 1.323948 -1.097333 -0.768619 1.320548 0.233246 -0.083031 -1.931873 2.189127 -0.051524 -1.647792 -0.728172 0.200191 -0.102758 0.460571 0.054086 -1.333049 1.564177 1.520115 1.532357 -0.521081 -1.037463 -0.413432 1.118277
1 0.213077 -1.061085 -0.997473 -1.446055 -0.024562 0.120896 -0.461501 -1.138477 0.983769 -0.140340 -0.302253 -0.540140 0.793527 0.011669 0.226834 -1.867136 -0.954558 -1.274738 -0.462769 -0.262035 -1.048895 -0.934456 0.617085 -1.197115 0.056404 1.499859 0.547669 2.797501 -0.625559 -0.248493 -0.453503 -0.836448 -1.779570 0.183616 0.102128 -1.385078 -0.585159 -0.112047 -0.303744 -0.213145 2.354225 0.598409 -2.154033 -1.973791 0.374794 0.577364 1.129823 -0.191984 0.377221 -0.233501 2.474922 -0.006907 -0.065430 0.965006 0.304154 0.533525 0.411437 -1.177894 0.611097 0.567003 0.988151 -0.638314 0.165525 -1.342050 -0.023097 1.631808 0.676776 -1.313850 -1.118955 1.015523 -0.433199 -0.524551 -0.274260 -0.301467 -0.890276 -1.546782 -0.246803 0.870468 1.689140 -0.803555 -0.800506 -0.053966 -1.538075 -0.874835 0.635541 -0.976896 0.904032 -0.418837 1.019360 0.120392 0.074966 0.599137 -0.716341 1.244792 1.453692 0.728159 0.481655 -0.064549 -0.381611 1.278603
2 1.470791 0.593878 0.836668 0.460491 1.042540 0.183481 -0.661539 0.115304 2.031085 1.242436 0.259781 -0.256159 -0.206609 -0.528230 -1.872724 1.588268 1.685884 0.018064 -2.079512 -1.543943 -0.148221 -0.272267 -1.278324 -0.442309 1.471981 1.018180 -0.337670 -0.573119 -0.139676 -0.497598 -1.020594 1.266699 2.295973 -0.716763 -0.311295 0.110729 0.610885 -0.484625 -0.939302 -1.236912 -0.509133 1.943533 1.367610 -1.490607 0.063574 -1.032744 -0.726389 -0.842815 -1.121529 0.171243 1.630980 -1.867818 0.351191 -1.275543 -1.545503 0.105977 2.001098 -1.247518 -0.345204 -0.462490 0.045033 0.198252 0.435874 0.751281 -0.483369 -0.883749 -0.706197 -1.346183 0.707285 0.130326 1.448559 -0.685684 0.152063 -0.958964 0.599144 -0.498841 -0.255264 -1.106058 0.056245 -1.865467 1.213610 -1.113450 -0.321455 0.460922 -1.322547 1.424683 2.218220 1.182406 -0.442274 1.862596 0.516616 0.540556 -1.486680 0.299545 -0.052014 -0.545246 -2.298098 -0.879502 -0.987752 0.372231
3 -0.121190 0.028235 0.229005 -1.772444 0.523793 1.313733 1.495456 -0.203124 -0.086773 -0.909066 0.084165 -0.768907 -1.054366 0.775486 -2.504936 1.924625 -0.909086 0.825028 2.387538 1.828123 0.115242 -0.326753 -1.404164 0.363681 -0.306493 1.905121 0.312672 -0.157399 -0.456277 0.206394 2.739692 1.334705 0.968743 -0.553691 -1.522574 1.322188 0.210698 -0.320464 0.912169 0.721823 0.472072 -0.801196 -1.041426 -0.561613 0.222571 0.527403 0.050054 1.618758 -0.415361 -0.500430 0.437452 0.575047 -0.228483 1.003212 0.215165 1.214890 0.939075 -0.335936 -1.669834 1.275661 -0.428725 -2.671502 -2.120515 -0.766720 -0.257375 0.350390 1.413539 -0.472909 -0.433935 -0.422629 0.367910 -1.466262 0.602139 2.266931 -0.162298 1.173774 -1.964278 0.582046 0.219679 -1.264104 -0.698571 -1.997247 0.831479 -1.377618 0.383037 0.282994 0.404398 -0.159537 1.508055 -1.592587 1.546873 -0.235228 1.451674 0.364401 0.213713 -1.878235 -1.089183 1.194839 0.055609 1.007122

HTML 转义#

假设您必须在 HTML 中显示 HTML,当渲染器无法区分时,这可能会有点麻烦。您可以使用 escape 格式化选项来处理这个问题,甚至可以在包含 HTML 本身的格式化器中使用它。

请注意,如果您在不受信任的用户提供的输入上使用 Styler 来提供 HTML,则应转义输入以防止安全漏洞。有关更多信息,请参阅 Jinja2 文档。

[66]:
df4 = pd.DataFrame([["<div></div>", '"&other"', "<span></span>"]])
df4.style
[66]:
  0 1 2
0
"&other"
[67]:
df4.style.format(escape="html")
[67]:
  0 1 2
0 <div></div> "&other" <span></span>
[68]:
df4.style.format(
    '<a href="https://pandas.ac.cn" target="_blank">{}</a>', escape="html"
)

导出到 Excel#

一些支持(自 0.20.0 版本起)可用于使用 OpenPyXLXlsxWriter 引擎将样式化的 DataFrames 导出到 Excel 工作表。处理的 CSS2.2 属性包括:

  • background-color

  • border-style 属性

  • border-width 属性

  • border-color 属性

  • color

  • font-family

  • font-style

  • font-weight

  • text-align

  • text-decoration

  • vertical-align

  • white-space: nowrap

  • 支持简写和边特定边框属性(例如 border-styleborder-left-style),以及用于所有边框的 border 简写(border: 1px solid green)或指定边框(border-left: 1px solid green)。使用 border 简写将覆盖之前设置的任何边框属性(有关更多详细信息,请参阅 CSS 工作组)。

  • 目前仅支持 CSS2 命名颜色和 #rgb 或 #rrggbb 形式的十六进制颜色。

  • 以下伪 CSS 属性也可用于设置 Excel 特定样式属性:

    • number-format

    • border-style(用于 Excel 特定样式:“hair”、“mediumDashDot”、“dashDotDot”、“mediumDashDotDot”、“dashDot”、“slantDashDot” 或 “mediumDashed”)

表级样式和数据单元格 CSS 类未包含在导出到 Excel 中:必须通过 Styler.apply 和/或 Styler.map 方法映射各个单元格的属性。

[69]:
df2.style.map(style_negative, props="color:red;").highlight_max(axis=0).to_excel(
    "styled.xlsx", engine="openpyxl"
)

输出的截图

Excel spreadsheet with styled DataFrame

导出到 LaTeX#

支持(自 1.3.0 版本起)将 Styler 导出到 LaTeX。有关 .to_latex 方法的文档提供了更多细节和大量示例。

更多关于 CSS 和 HTML#

层叠样式表 (CSS) 语言旨在影响浏览器如何渲染 HTML 元素,它有其自身的特殊性。它从不报告错误:它只是默默地忽略它们,并且不会按照您预期的方式渲染您的对象,因此有时可能会令人沮丧。这里是对 Styler 如何创建 HTML 和与 CSS 交互的简要介绍,以及避免常见陷阱的建议。

CSS 类和 ID#

附加到每个单元格的 CSS class 的精确结构如下。

  • 具有索引和列名称的单元格包括 index_namelevel<k>,其中 k 是它在 MultiIndex 中的级别。

  • 索引标签单元格包括:

    • row_heading

    • level<k>,其中 k 是 MultiIndex 中的级别。

    • row<m>,其中 m 是行的数字位置。

  • 列标签单元格包括:

    • col_heading

    • level<k>,其中 k 是 MultiIndex 中的级别。

    • col<n>,其中 n 是列的数字位置。

  • 数据单元格包括:

    • data

    • row<m>,其中 m 是单元格的数字位置。

    • col<n>,其中 n 是单元格的数字位置。

  • 空白单元格包括 blank

  • 修剪过的单元格包括 col_trimrow_trim

ID 的结构是 T_uuid_level<k>_row<m>_col<n>,其中 level<k> 仅用于标题,并且标题只会拥有 row<m>col<n>,以其中一个需要的为准。默认情况下,我们还在每个行/列标识符前面加上一个每个 DataFrame 唯一的 UUID,这样来自一个 DataFrame 的样式就不会与同一笔记本或页面中另一个 DataFrame 的样式发生冲突。您可以在 优化 中了解有关 UUID 使用的更多信息。

通过调用 .to_html() 方法,我们可以看到 HTML 的示例。

[70]:
print(
    pd.DataFrame(
        [[1, 2], [3, 4]], index=["i1", "i2"], columns=["c1", "c2"]
    ).style.to_html()
)
<style type="text/css">
</style>
<table id="T_30010">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_30010_level0_col0" class="col_heading level0 col0" >c1</th>
      <th id="T_30010_level0_col1" class="col_heading level0 col1" >c2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_30010_level0_row0" class="row_heading level0 row0" >i1</th>
      <td id="T_30010_row0_col0" class="data row0 col0" >1</td>
      <td id="T_30010_row0_col1" class="data row0 col1" >2</td>
    </tr>
    <tr>
      <th id="T_30010_level0_row1" class="row_heading level0 row1" >i2</th>
      <td id="T_30010_row1_col0" class="data row1 col0" >3</td>
      <td id="T_30010_row1_col1" class="data row1 col1" >4</td>
    </tr>
  </tbody>
</table>

CSS 层次结构#

示例表明,当 CSS 样式重叠时,HTML 渲染中最后出现的样式具有优先权。因此,以下结果不同:

[71]:
df4 = pd.DataFrame([["text"]])
df4.style.map(lambda x: "color:green;").map(lambda x: "color:red;")
[71]:
  0
0 text
[72]:
df4.style.map(lambda x: "color:red;").map(lambda x: "color:green;")
[72]:
  0
0 text

这仅适用于具有相同层次结构或重要性的 CSS 规则。您可以在这里阅读更多关于 CSS 特效性 的内容,但对于我们的目的来说,足以总结要点:

每个 HTML 元素的 CSS 重要性分数是通过从零开始并加上以下值计算得出的:

  • 1000 为内联样式属性

  • 100 为每个 ID

  • 10 为每个属性、类或伪类

  • 1 为每个元素名称或伪元素

让我们用这个来描述以下配置的操作:

[73]:
df4.style.set_uuid("a_").set_table_styles(
    [{"selector": "td", "props": "color:red;"}]
).map(lambda x: "color:green;")
[73]:
  0
0 text

此文本为红色,因为生成的选择器 #T_a_ td 的值为 101(ID 加上元素),而 #T_a_row0_col0 的值仅为 100(ID),因此被认为次要,即使在 HTML 中它排在前面之后。

[74]:
df4.style.set_uuid("b_").set_table_styles(
    [
        {"selector": "td", "props": "color:red;"},
        {"selector": ".cls-1", "props": "color:blue;"},
    ]
).map(lambda x: "color:green;").set_td_classes(pd.DataFrame([["cls-1"]]))
[74]:
  0
0 text

在上例中,文本为蓝色,因为选择器 #T_b_ .cls-1 的值为 110(ID 加上类),这具有优先权。

[75]:
df4.style.set_uuid("c_").set_table_styles(
    [
        {"selector": "td", "props": "color:red;"},
        {"selector": ".cls-1", "props": "color:blue;"},
        {"selector": "td.data", "props": "color:yellow;"},
    ]
).map(lambda x: "color:green;").set_td_classes(pd.DataFrame([["cls-1"]]))
[75]:
  0
0 text

现在我们创建了另一个表格样式,这次选择器 T_c_ td.data(ID 加上元素加上类)被提升到 111。

如果您的样式未能应用,并且这真的很令人沮丧,请尝试使用 !important 王牌。

[76]:
df4.style.set_uuid("d_").set_table_styles(
    [
        {"selector": "td", "props": "color:red;"},
        {"selector": ".cls-1", "props": "color:blue;"},
        {"selector": "td.data", "props": "color:yellow;"},
    ]
).map(lambda x: "color:green !important;").set_td_classes(pd.DataFrame([["cls-1"]]))
[76]:
  0
0 text

终于得到了绿色文本!

可扩展性#

pandas 的核心是,并且将继续是其“高性能、易于使用的数据结构”。牢记这一点,我们希望 DataFrame.style 能实现两个目标:

  • 提供一个 API,该 API 在交互式使用时令人愉悦,并且对于许多任务来说“足够好”。

  • 为专用库提供构建基础。

如果您在此基础上构建了一个很棒的库,请告诉我们,我们将 链接 到它。

子类化#

如果默认模板不能完全满足您的需求,您可以子类化 Styler 并扩展或覆盖模板。我们将展示一个扩展默认模板以在每个表之前插入自定义标题的示例。

[77]:
from jinja2 import Environment, ChoiceLoader, FileSystemLoader
from IPython.display import HTML
from pandas.io.formats.style import Styler

我们将使用以下模板:

[78]:
with open("templates/myhtml.tpl") as f_html:
    print(f_html.read())
{% extends "html_table.tpl" %}
{% block table %}
<h1>{{ table_title|default("My Table") }}</h1>
{{ super() }}
{% endblock table %}

现在我们已经创建了一个模板,我们需要设置一个知道它的 Styler 子类。

[79]:
class MyStyler(Styler):
    env = Environment(
        loader=ChoiceLoader(
            [
                FileSystemLoader("templates"),  # contains ours
                Styler.loader,  # the default
            ]
        )
    )
    template_html_table = env.get_template("myhtml.tpl")

请注意,我们在环境的加载器中包含了原始加载器。这是因为我们扩展了原始模板,所以 Jinja 环境需要能够找到它。

现在我们可以使用这个自定义 styler。它的 __init__ 接受一个 DataFrame。

[80]:
MyStyler(df3)
[80]:

我的表格

    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

我们的自定义模板接受一个 table_title 关键字。我们可以在 .to_html 方法中提供该值。

[81]:
HTML(MyStyler(df3).to_html(table_title="Extending Example"))
[81]:

扩展示例

    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

为了方便起见,我们提供了 Styler.from_custom_template 方法,它与自定义子类执行相同的操作。

[82]:
EasyStyler = Styler.from_custom_template("templates", "myhtml.tpl")
HTML(EasyStyler(df3).to_html(table_title="Another Title"))
[82]:

另一个标题

    c1 c2 c3 c4
A r1 0.295787 -2.213722 -1.695725 -1.409669
r2 -1.532179 -0.167794 -0.142344 1.022587
B r1 0.253825 1.770438 0.631995 1.202775
r2 -1.078887 -1.674201 -1.583150 0.487844

模板结构#

这是样式生成模板和表格生成模板的模板结构:

样式模板

[84]:
HTML(style_structure)
[84]:
before_style
style
<style type="text/css">
table_styles
before_cellstyle
cellstyle
</style>

表格模板

[86]:
HTML(table_structure)
[86]:
before_table
table
<table ...>
caption
thead
before_head_rows
head_tr(循环遍历标题)
after_head_rows
tbody
before_rows
tr(循环遍历数据行)
after_rows
</table>
after_table

有关更多详细信息,请参阅 GitHub 仓库 中的模板。