表格可视化#

这一节演示如何使用 Styler 班级。有关图表可视化的信息,请参阅 Chart Visualization 。本文档以Jupyter笔记本的形式编写,可供查看或下载 here

Styler对象和HTML#

样式设置应在处理完DataFrame中的数据后执行。这个 Styler 创建一个HTML <table> and leverages CSS styling language to manipulate many parameters including colors, fonts, borders, background, etc. See here 有关设置HTML表样式的更多信息。这使得开箱即用的灵活性很大,甚至使Web开发人员能够将DataFrame集成到他们现有的用户界面设计中。

这个 DataFrame.style attribute is a property that returns a Styler 对象。它有一个 _repr_html_ 方法,以便在Jupyter Notebook中自动呈现它们。

[2]:
import pandas as pd
import numpy as np
import matplotlib as mpl

df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]],
                  index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'),
                  columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:']))
df.style
[2]:
Model: Decision Tree Regression Random
Predicted: Tumour Non-Tumour Tumour Non-Tumour Tumour Non-Tumour
Actual Label:            
Tumour (Positive) 38.000000 2.000000 18.000000 22.000000 21 nan
Non-Tumour (Negative) 19.000000 439.000000 6.000000 452.000000 226 232.000000

上面的输出看起来与标准的DataFrame HTML表示非常相似。但是这里的HTML已经为每个单元格附加了一些CSS类,即使我们还没有创建任何样式。我们可以通过调用 .to_html() 方法,该方法以字符串的形式返回原始的HTML,这对于进一步处理或添加到文件中非常有用-请参阅 More about CSS and HTML 。下面,我们将展示如何使用它们来格式化DataFrame,使其更具通信性。例如,我们可以如何构建 s

[4]:
s
[4]:
Confusion matrix for multiple cancer prediction models.
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

设置显示格式#

设置值的格式#

在添加样式之前,最好先说明 Styler 可以辨别出 显示 来自 实际 值,在数据区和索引头或列头中。为了控制显示值,文本以字符串的形式打印在每个单元格中,我们可以使用 .format().format_index() 方法,以根据 format spec string 或者是接受单个值并返回字符串的可调用函数。可以为整个表、索引、单独的列或多索引级别定义它。

此外,Format函数还具有 精度 参数专门帮助设置浮点数的格式,以及 十进制数千人 分隔符以支持其他区域设置,以及 na_rep 参数来显示缺少的数据,以及一个 逃脱 参数以帮助显示Safe-Html或Safe-LaTeX。默认格式化程序配置为采用Pandas的 styler.format.precision 可选,可使用 with pd.option_context('format.precision', 2):

[5]:
df.style.format(precision=0, na_rep='MISSING', thousands=" ",
                formatter={('Decision Tree', 'Tumour'): "{:.2f}",
                           ('Regression', 'Non-Tumour'): lambda x: "$ {:,.1f}".format(x*-1e6)
                          })
[5]:
Model: Decision Tree Regression Random
Predicted: Tumour Non-Tumour Tumour Non-Tumour Tumour Non-Tumour
Actual Label:            
Tumour (Positive) 38.00 2 18 $ -22 000 000.0 21 MISSING
Non-Tumour (Negative) 19.00 439 6 $ -452 000 000.0 226 232

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

[6]:
weather_df = pd.DataFrame(np.random.rand(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
[6]:
Tokyo Beijing
2021-01-01 3.215134 3.844444
2021-01-02 3.994919 4.933420
2021-01-03 2.897186 1.224547
2021-01-04 1.291026 4.537056
2021-01-05 1.994123 0.757314
2021-01-06 3.429587 2.896616
2021-01-07 1.912253 2.767986
2021-01-08 2.354040 1.566938
2021-01-09 0.971751 3.088100
2021-01-10 0.109126 3.966052
[7]:
weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
[7]:
Weather Conditions
  Tokyo Beijing
Monday Dry Heavy Rain
Tuesday Rain Dry
Wednesday Heavy Rain Heavy Rain
Thursday Rain Heavy Rain
Friday Rain Dry

隐藏数据#

索引和列标题可以完全隐藏,也可以再选择要排除的行或列。这两个选项都使用相同的方法执行。

可以通过调用 .hide() 不带任何参数,如果您的索引是基于整数的,这可能会很有用。同样,列标题也可以通过调用 .hide(axis=“columns”) 没有任何进一步的争论。

特定行或列可以通过调用 .hide() 方法,并将行/列标签、类似列表的标签或一段行/列标签传递给 subset 论点。

隐藏不会更改CSS类的整数排列,例如,隐藏DataFrame的前两列意味着列类索引仍将从 col2 ,因为 col0col1 被简单地忽视了。

我们可以更新我们的 Styler 对象来隐藏一些数据并设置值的格式。

[8]:
s = df.style.format('{:.0f}').hide([('Random', 'Tumour'), ('Random', 'Non-Tumour')], axis="columns")
s
[8]:
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

添加样式的方法#

确实有 添加自定义css样式的3种主要方法Styler

  • 使用 .set_table_styles() 使用指定的内部css控制表的更大区域。尽管表格样式允许灵活地添加控制表格所有单独部分的CSS选择器和属性,但对于单个单元格规范来说,它们很笨拙。另外,请注意,表格样式不能导出到Excel。

  • 使用 .set_td_classes() 要将外部CSS类直接链接到数据单元格,或将由 .set_table_styles() 。看见 here 。它们不能用于列标题行或索引,也不能导出到Excel。

  • 使用 .apply().applymap() 用于将直接内部CS添加到特定数据单元格的函数。看见 here 。从v1.4.0开始,也有直接处理列标题行或索引的方法; .apply_index().applymap_index() 。请注意,只有这些方法才会添加将导出到Excel的样式。这些方法的工作方式类似于 DataFrame.apply()DataFrame.applymap()

表格样式#

表格样式足够灵活,可以控制表的所有单独部分,包括列标题和索引。但是,对于单个数据单元格或任何类型的条件格式,它们的类型可能很不方便,因此我们建议将表格样式用于广泛的样式,例如一次整行或整列。

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

为了复制正常格式的CSS选择器和属性(属性值对),例如

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

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

[10]:
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])
[10]:
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

接下来,我们只需添加两个针对表的特定部分的样式构件。在这里要小心,因为我们 链接方法 我们需要显式指示该方法 不是为了 overwrite 现有的样式。

[12]:
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)
[12]:
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

作为一种方便的方法( 从1.2.0版开始 )我们还可以传递一个 dict.set_table_styles() 它包含行或列键。在幕后,Styler只是对键进行索引并添加相关的 .col<m>.row<n> 根据需要为给定的css选择器初始化。

[14]:
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)
[14]:
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

设置类并链接到外部css#

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

表属性#

很容易添加一个 class to the main <table> using .set_table_attributes() 。此方法还可以附加内联样式-请参阅 CSS Hierarchies

[16]:
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,其索引和列与基础 Styler 的DataFrame。该DataFrame将包含以css类形式添加到单个数据单元格的字符串: <td> elements of the <table>. Rather than use external CSS we will create our classes internally and add them to table style. We will save adding the borders until the section on tooltips

[17]:
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)
[17]:
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

Styler函数#

对数据采取行动#

我们使用以下方法来传递您的样式函数。这两种方法都接受一个函数(和其他一些关键字参数),并以某种方式将其应用于DataFrame,呈现CSS样式。

  • .applymap() (按元素):接受接受单个值的函数,并返回带有css属性-值对的字符串。

  • .apply() (列/行/表):接受接受Series或DataFrame的函数,并返回具有相同形状的Series、DataFrame或Numpy数组,其中每个元素都是一个带有一个css属性值对的字符串。此方法一次传递DataFrame的每一列或行或一次传递整个表,具体取决于 axis 关键字参数。用于分栏使用 axis=0 ,按行使用 axis=1 ,并且一次对整个表使用 axis=None

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

[19]:
np.random.seed(0)
df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
df2.style
[19]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

例如,我们可以构建一个函数,用于在文本为负值时对其进行着色,并将其与部分淡入淡出可以忽略不计的单元格的函数相关联。因为它依次查看我们使用的每个元素 applymap

[20]:
def style_negative(v, props=''):
    return props if v < 0 else None
s2 = df2.style.applymap(style_negative, props='color:red;')\
              .applymap(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)
s2
[20]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

我们还可以构建一个函数,一次高亮显示所有行、COLS和DataFrame中的最大值。在本例中,我们使用 apply 。下面我们在一列中突出显示最大值。

[22]:
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)
[22]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

我们可以在不同的轴上使用相同的函数,在这里用紫色突出显示DataFrame最大值,用粉色突出显示行最大值。

[24]:
s2.apply(highlight_max, props='color:white;background-color:pink;', axis=1)\
  .apply(highlight_max, props='color:white;background-color:purple', axis=None)
[24]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

最后一个示例显示了某些样式如何被其他样式覆盖。通常,应用的最新样式是活动的,但您可以在 section on CSS hierarchies 。您还可以将这些样式应用到DataFrame的更细粒度部分-请参阅 subset slicing

仅使用类就可以复制其中的一些功能,但可能会更加繁琐。看见 item 3) of Optimization

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

对索引和列标题执行操作#

通过使用以下命令,可以获得类似的标题应用:

  • .applymap_index() (按元素):接受接受单个值的函数,并返回带有css属性-值对的字符串。

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

您可以选择一个 level 属于 MultiIndex 但目前还没有类似的 subset 对于这些方法,可以使用应用程序。

[26]:
s2.applymap_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)
[26]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

工具提示和标题#

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

[27]:
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)
[27]:
Confusion matrix for multiple cancer prediction models.
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

添加工具提示( 从1.3.0版开始 )可以使用 .set_tooltips() 方法,您可以通过提供具有相交索引和列的基于字符串的DataFrame来向数据单元格添加CSS类。您不必指定 css_class 名称或任何CSS props 对于工具提示,因为有标准的默认设置,但如果您想要更多的可视控制,可以选择。

[29]:
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;')
[29]:
Confusion matrix for multiple cancer prediction models.
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

对于我们的表格,剩下的唯一要做的就是添加突出显示边框,以将观众的注意力吸引到工具提示上。我们将像以前一样使用表样式创建内部css类。 设置类始终覆盖 因此,我们需要确保添加前面的类。

[31]:
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)
[31]:
Confusion matrix for multiple cancer prediction models.
Model: Decision Tree Regression
Predicted: Tumour Non-Tumour Tumour Non-Tumour
Actual Label:        
Tumour (Positive) 38 2 18 22
Non-Tumour (Negative) 19 439 6 452

通过切片实现更精细的控制#

到目前为止,我们为 Styler.applyStyler.applymap 函数尚未演示如何使用 subset 争论。这是一个允许很大灵活性的有用参数:它允许您将样式应用到特定的行或列,而不必将该逻辑编码到 style 功能。

传递给 subset 其行为类似于对DataFrame进行切片;

  • 标量被视为列标签

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

  • 元组被视为 (row_indexer, column_indexer)

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

[33]:
df3 = pd.DataFrame(np.random.randn(4,4),
                   pd.MultiIndex.from_product([['A', 'B'], ['r1', 'r2']]),
                   columns=['c1','c2','c3','c4'])
df3
[33]:
c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

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

[34]:
slice_ = ['c3', 'c4']
df3.style.apply(highlight_max, props='color:red;', axis=0, subset=slice_)\
         .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)
[34]:
    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

如果与 IndexSlice 正如所建议的那样,它可以更灵活地跨两个维度进行索引。

[35]:
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_)
[35]:
    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

属性一起使用时,还提供了子选择行的灵活性 axis=1

[36]:
slice_ = idx[idx[:,'r2'], :]
df3.style.apply(highlight_max, props='color:red;', axis=1, subset=slice_)\
         .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)
[36]:
    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

此外,还可以提供 条件过滤

假设我们只想在第1列和第3列之和小于-2.0的情况下突出显示第2列和第4列的最大值 (基本上不包括行 (:,'r2') )

[37]:
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_)
[37]:
    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

目前只支持基于标签的切片,不支持位置切片,也不支持可伸缩切片。

如果您的样式函数使用 subsetaxis 关键字参数,请考虑将函数包装在 functools.partial ,分割出那个关键字。

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

优化#

通常,对于较小的表和大多数情况,呈现的HTML不需要优化,我们并不真正推荐这样做。有两种情况值得考虑:

  • 如果要呈现非常大的HTML表并设置其样式,某些浏览器会出现性能问题。

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

在此,我们建议实施以下步骤:

1.删除UUID和CELL_ID#

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

这是次优的:

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

这样更好:

[39]:
from pandas.io.formats.style import Styler
s4 = Styler(df4, uuid_len=0, cell_ids=False)

2.使用表格样式#

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

这是次优的:

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

这样更好:

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

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

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

这是次优的:

[42]:
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)
[42]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

这样更好:

[43]:
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)
[43]:
  A B C D
0 1.764052 0.400157 0.978738 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 -0.854096
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

4.不要使用工具提示#

工具提示需要 cell_ids 并为其生成额外的HTML元素 每个 数据单元格。

5.如果每个字节都计数,则使用字符串替换#

您可以删除不必要的HTML,或通过替换默认的CSS词典来缩短默认的类名。您可以阅读更多关于CSS的内容 below

[44]:
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>

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

内置样式#

一些样式函数非常常见,我们已将它们“内置”到 Styler ,因此您不必自己编写和应用它们。目前这类函数的列表如下:

关于每个函数的单独文档通常会给出更多的例子来说明它们的论点。

高亮显示空#

[46]:
df2.iloc[0,2] = np.nan
df2.iloc[4,3] = np.nan
df2.loc[:4].style.highlight_null(color='yellow')
[46]:
  A B C D
0 1.764052 0.400157 nan 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 nan

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

[47]:
df2.loc[:4].style.highlight_max(axis=1, props='color:white; font-weight:bold; background-color:darkblue;')
[47]:
  A B C D
0 1.764052 0.400157 nan 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 nan

高亮显示之间#

如果索引匹配,此方法接受范围作为Float、NumPy数组或Series。

[48]:
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;')
[48]:
  A B C D
0 1.764052 0.400157 nan 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 nan

突出显示分位数#

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

[49]:
df2.loc[:4].style.highlight_quantile(q_left=0.85, axis=None, color='yellow')
[49]:
  A B C D
0 1.764052 0.400157 nan 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 nan

背景渐变和文本渐变#

您可以使用 background_gradient and text_gradient methods. These require matplotlib, and we’ll use Seaborn 才能得到一张漂亮的色表。

[50]:
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)

df2.style.background_gradient(cmap=cm)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Input In [50], in <cell line: 1>()
----> 1 import seaborn as sns
      2 cm = sns.light_palette("green", as_cmap=True)
      4 df2.style.background_gradient(cmap=cm)

ModuleNotFoundError: No module named 'seaborn'
[51]:
df2.style.text_gradient(cmap=cm)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [51], in <cell line: 1>()
----> 1 df2.style.text_gradient(cmap=cm)

NameError: name 'cm' is not defined

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

设置属性#

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

[52]:
df2.loc[:4].style.set_properties(**{'background-color': 'black',
                           'color': 'lawngreen',
                           'border-color': 'white'})
[52]:
  A B C D
0 1.764052 0.400157 nan 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 nan

条形图#

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

[53]:
df2.style.bar(subset=['A', 'B'], color='#d65f5f')
[53]:
  A B C D
0 1.764052 0.400157 nan 2.240893
1 1.867558 -0.977278 0.950088 -0.151357
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
4 1.494079 -0.205158 0.313068 nan
5 -2.552990 0.653619 0.864436 -0.742165
6 2.269755 -1.454366 0.045759 -0.187184
7 1.532779 1.469359 0.154947 0.378163
8 -0.887786 -1.980796 -0.347912 0.156349
9 1.230291 1.202380 -0.387327 -0.302303

附加的关键字参数使您可以更好地控制居中和定位,并且可以传递 [color_negative, color_positive] 以突出显示较低和较高的值或matplotlib色彩映射。

为了展示一个示例,下面是如何使用新的 align 选项,与设置相结合 vminvmax 限制,即 width 和底层的css props 单元格,留出空间来显示文本和条形图。我们还使用 text_gradient 使用matplotlib颜色贴图使文本的颜色与条形图相同(尽管在这种情况下,没有这种额外效果的可视化效果可能会更好)。

[54]:
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)
[54]:
  A B C D
0 1.764 0.400 2.241
1 1.868 -0.977 0.950 -0.151
2 -0.103 0.411 0.144 1.454
3 0.761 0.122 0.444 0.334
4 1.494 -0.205 0.313
5 -2.553 0.654 0.864 -0.742
6 2.270 -1.454 0.046 -0.187
7 1.533 1.469 0.155 0.378
8 -0.888 -1.981 -0.348 0.156
9 1.230 1.202 -0.387 -0.302

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

[56]:
HTML(head)
[56]:
Align All Negative Both Neg and Pos All Positive Large Positive
left
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
right
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
zero
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
mid
-100
-60
-30
-20
-10
-5
0
90
10
20
50
100
100
103
101
102
mean
-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

[57]:
style1 = df2.style\
            .applymap(style_negative, props='color:red;')\
            .applymap(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
[57]:
A B C D
1.764052 0.400157 nan 2.240893
1.867558 -0.977278 0.950088 -0.151357
-0.103219 0.410599 0.144044 1.454274
0.761038 0.121675 0.443863 0.333674
1.494079 -0.205158 0.313068 nan
-2.552990 0.653619 0.864436 -0.742165
2.269755 -1.454366 0.045759 -0.187184
1.532779 1.469359 0.154947 0.378163
-0.887786 -1.980796 -0.347912 0.156349
1.230291 1.202380 -0.387327 -0.302303
[58]:
style2 = df3.style
style2.use(style1.export())
style2
[58]:
c1 c2 c3 c4
-1.048553 -1.420018 -1.706270 1.950775
-0.509652 -0.438074 -1.252795 0.777490
-1.613898 -0.212740 -0.895467 0.386902
-0.510805 -1.180632 -0.028182 0.428332

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

限制#

  • 仅限DataFrame(使用 Series.to_frame().style )

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

  • 没有很大的REPR,施工性能也不是很好;尽管我们有一些 HTML optimizations

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

其他有趣和有用的东西#

这里有几个有趣的例子。

小组件#

Styler 与窗口小部件的交互非常好。如果你在网上查看,而不是自己操作笔记本,你就错过了交互式调整调色板的机会。

[59]:
from ipywidgets import widgets
@widgets.interact
def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(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,
                                            as_cmap=True)
    )

放大#

[60]:
def magnify():
    return [dict(selector="th",
                 props=[("font-size", "4pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]
[61]:
np.random.seed(25)
cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
bigdf = pd.DataFrame(np.random.randn(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())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [61], in <cell line: 2>()
      1 np.random.seed(25)
----> 2 cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
      3 bigdf = pd.DataFrame(np.random.randn(20, 25)).cumsum()
      5 bigdf.style.background_gradient(cmap, axis=1)\
      6     .set_properties(**{'max-width': '80px', 'font-size': '1pt'})\
      7     .set_caption("Hover to magnify")\
      8     .format(precision=2)\
      9     .set_table_styles(magnify())

NameError: name 'sns' is not defined

粘性标题#

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

[62]:
bigdf = pd.DataFrame(np.random.randn(16, 100))
bigdf.style.set_sticky(axis="index")
[62]:
  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 0.228273 1.026890 -0.839585 -0.591182 -0.956888 -0.222326 -0.619915 1.837905 -2.053231 0.868583 -0.920734 -0.232312 2.152957 -1.334661 0.076380 -1.246089 1.202272 -1.049942 1.056610 -0.419678 2.294842 -2.594487 2.822756 0.680889 -1.577693 -1.976254 0.533340 -0.290870 -0.513520 1.982626 0.226001 -1.839905 1.607671 0.388292 0.399732 0.405477 0.217002 -0.633439 0.246622 -1.939546 0.114060 -1.885341 0.243080 -0.705481 0.364628 -0.502952 -0.225752 -0.565538 0.103395 2.018408 1.094248 1.662434 -0.627453 1.621200 1.178133 -0.374879 -0.544329 0.287761 -0.205820 1.189988 0.728927 -0.222040 -1.622706 0.312541 -1.160421 0.313560 0.471998 0.577862 0.505407 -0.626488 -0.346369 -2.065942 0.768936 1.128866 0.166924 -0.967255 0.491996 -0.550857 -0.084694 1.967568 -0.062675 -0.851136 0.426521 -0.277561 -1.377945 -0.095196 0.833639 -0.784754 1.046145 -0.645784 -1.891579 -0.097333 -1.358895 0.498310 -1.147321 -0.536521 -0.916489 -0.212148 0.192844 -0.322683
1 -1.727654 0.764067 0.445314 -2.135576 1.020364 -0.587397 0.048037 0.560169 1.424193 -0.003191 -0.297766 0.232724 0.671954 -1.346282 -0.601723 -0.169196 -0.658381 -0.196024 0.177552 0.032294 1.303258 -0.539484 0.529918 0.382797 1.800623 2.513618 -0.245011 0.208728 -0.300852 0.152992 0.030979 -0.324954 -0.777273 -0.337442 -2.020510 1.419771 -0.741890 -1.559918 0.966290 -0.182294 2.027541 -1.090301 0.430032 -0.730951 0.164135 -0.673210 -0.168668 -0.541845 -0.352464 1.688785 0.092362 1.121011 -0.451224 0.872053 -1.142141 -0.859672 0.930692 -0.177927 -2.158403 -0.289260 -0.904782 0.487616 -0.041970 0.649388 0.019125 -0.977803 -1.972866 -1.266139 -1.000965 -3.049890 0.394720 -1.947339 0.533330 0.379163 2.040071 0.307235 -0.669187 -0.196576 0.922861 1.727249 -0.775059 1.366756 1.693871 -1.282804 -1.932243 -2.063496 -0.395541 1.925655 -0.503716 -1.558305 1.380012 -2.169335 -1.269709 0.905344 0.737179 -1.260360 1.201543 -0.367450 0.878851 0.844085
2 1.351855 1.115809 -1.030206 -0.444282 0.057423 -0.562746 0.004501 0.173643 0.970628 1.867282 0.119880 0.640622 -2.553511 -0.439966 -0.062954 -0.067075 -0.396659 0.405585 -0.749193 -0.653916 -0.167081 1.410437 0.259248 -0.989426 -1.583010 -0.539820 -0.264962 -1.156517 -0.147415 1.063123 0.549318 1.387270 -0.286247 1.573611 0.962956 0.807019 -0.562733 -0.923400 -0.414296 0.003842 -2.096592 -1.858677 -0.968215 0.456882 -0.110648 1.385829 -1.082738 -1.089539 0.595603 0.081374 1.684345 0.305161 0.590335 -0.177260 0.730379 0.147656 -0.150377 0.243728 -0.263203 -0.378285 0.340001 1.544692 0.579486 1.301523 0.085383 -0.826915 0.680524 -1.034403 -1.110716 0.099092 -2.411402 -0.795409 -0.596730 2.016938 0.650740 -0.205659 -1.367066 1.731274 -0.400586 -1.877268 1.997468 0.610815 0.194705 1.178263 0.110523 0.946986 0.157934 1.319965 1.398984 0.049304 -1.106371 -0.376500 2.061808 -1.546407 0.276935 -0.646731 -0.173810 -0.176011 0.289851 0.024213
3 1.329898 -0.251138 -0.892670 -0.886607 0.023848 -2.151303 0.317010 0.936555 -1.793396 0.407319 1.407526 0.669217 -0.063702 -1.134419 0.643766 0.016192 0.584973 0.572833 0.074078 -0.448167 0.032590 -1.096528 0.745444 1.112199 -0.233729 -0.873415 0.230934 -0.805410 0.216766 0.835699 -0.609935 -2.504445 1.268726 0.276230 -0.600436 -1.180951 -0.294444 1.372700 -1.209484 0.178217 0.739316 -0.013644 -1.148450 2.496847 1.112560 0.085375 0.288464 0.359711 -0.547638 1.113638 1.464883 -0.127626 -0.015008 0.467636 -0.544390 0.020004 0.705605 -2.420518 -0.373968 0.467792 -1.684673 -0.616189 3.774140 0.749130 0.888204 -0.307561 0.895529 -0.503150 -2.521870 1.241118 -0.591644 -0.657826 0.890374 0.238272 0.822878 1.866971 0.985183 -0.096968 -0.677218 -0.310448 -0.061652 0.434656 0.113166 -0.122837 -0.003245 -0.188587 0.474867 0.586855 0.721862 0.983135 -0.208411 0.947936 0.067164 -0.100554 1.066966 0.435700 -1.908924 -0.773551 0.580472 -1.620192
4 -1.567793 -0.972316 1.536337 -1.046018 0.128710 0.780459 0.558835 -0.402247 -1.785758 1.913771 1.390267 -2.093964 1.585005 0.788355 0.088875 0.453289 0.209618 1.461669 0.164643 0.215340 0.647726 -1.852759 -0.514054 -0.528535 -0.978868 1.563941 0.228150 -1.091756 -0.451212 0.538402 -0.064286 -0.278562 1.297073 0.064941 2.050824 -0.517423 0.456448 -0.021227 0.247564 0.869639 1.539611 0.572745 -0.185547 -0.931420 -1.279881 1.396666 0.552607 1.484888 1.193997 -0.236963 0.350956 1.253611 0.686695 -0.394330 0.549364 -0.742711 -0.465343 1.352667 -0.075703 -2.197694 -0.338980 -0.203617 1.701557 -1.170804 0.747205 0.226150 0.725443 0.611623 0.605679 -0.465381 1.056823 2.836512 -0.126174 -0.286708 -0.311325 -1.959020 0.408000 -1.252445 0.044938 0.066002 -0.778297 -0.304053 -1.400471 -0.355749 -1.671326 0.633932 0.804110 -1.034119 -2.847751 -1.121103 0.430543 -0.971643 -0.706059 -0.416779 1.236913 -0.253807 -0.924209 -0.597519 0.414284 -0.450197
5 -0.773866 -0.240521 -0.217165 1.173609 0.686390 0.008358 0.696232 0.173166 0.620498 0.504067 0.428066 -0.051824 0.719915 0.057165 0.562808 -0.369536 0.483399 0.620765 -0.354342 -1.469471 -1.937266 0.038031 -1.518162 -0.417599 0.386717 0.716193 0.489961 0.733957 0.914415 0.679894 0.255448 -0.508338 0.332030 -0.111107 -0.251983 -1.456620 0.409630 1.062320 -0.577115 0.718796 -0.399260 -1.311389 0.649122 0.091566 0.628872 0.297894 -0.142290 -0.542291 -0.914290 1.144514 0.313584 1.182635 1.214235 -0.416446 -1.653940 -2.550787 0.442473 0.052127 -0.464469 -0.523852 0.989726 -1.325539 -0.199687 -1.226727 0.290018 1.164574 0.817841 -0.309509 0.496599 0.943536 -0.091850 -2.802658 2.126219 -0.521161 0.288098 -0.454663 -1.676143 -0.357661 -0.788960 0.185911 -0.017106 2.454020 1.832706 -0.911743 -0.655873 -0.000514 -2.226997 0.677285 -0.140249 -0.408407 -0.838665 0.482228 1.243458 -0.477394 -0.220343 -2.463966 0.237325 -0.307380 1.172478 0.819492
6 0.405906 -0.978919 1.267526 0.145250 -1.066786 -2.114192 -1.128346 -1.082523 0.372216 0.004127 -0.211984 0.937326 -0.935890 -1.704118 0.611789 -1.030015 0.636123 -1.506193 1.736609 1.392958 1.009424 0.353266 0.697339 -0.297424 0.428702 -0.145346 -0.333553 -0.974699 0.665314 0.971944 0.121950 -1.439668 1.018808 1.442399 -0.199585 -1.165916 0.645656 1.436466 -0.921215 1.293906 -2.706443 1.460928 -0.823197 0.292952 -1.448992 0.026692 -0.975883 0.392823 0.442166 0.745741 1.187982 -0.218570 0.305288 0.054932 -1.476953 -0.114434 0.014103 0.825394 -0.060654 -0.413688 0.974836 1.339210 1.034838 0.040775 0.705001 0.017796 1.867681 -0.390173 2.285277 2.311464 -0.085070 -0.648115 0.576300 -0.790087 -1.183798 -1.334558 -0.454118 0.319302 1.706488 0.830429 0.502476 -0.079631 0.414635 0.332511 0.042935 -0.160910 0.918553 -0.292697 -1.303834 -0.199604 0.871023 -1.370681 -0.205701 -0.492973 1.123083 -0.081842 -0.118527 0.245838 -0.315742 -0.511806
7 0.011470 -0.036104 1.399603 -0.418176 -0.412229 -1.234783 -1.121500 1.196478 -0.569522 0.422022 -0.220484 0.804338 2.892667 -0.511055 -0.168722 -1.477996 -1.969917 0.471354 1.698548 0.137105 -0.762052 0.199379 -0.964346 -0.256692 1.265275 0.848762 -0.784161 1.863776 -0.355569 0.854552 0.768061 -2.075718 -2.501069 1.109868 0.957545 -0.683276 0.307764 0.733073 1.706250 -1.118091 0.374961 -1.414503 -0.524183 -1.662696 0.687921 0.521732 1.451396 -0.833491 -0.362796 -1.174444 -0.813893 -0.893220 0.770743 1.156647 -0.647444 0.125929 0.513600 -0.537874 1.992052 -1.946584 -0.104759 0.484779 -0.290936 -0.441075 0.542993 -1.050038 1.630482 0.239771 -1.177310 0.464804 -0.966995 0.646086 0.486899 1.022196 -2.267827 -1.229616 1.313805 1.073292 2.324940 -0.542720 -1.504292 0.777643 -0.618553 0.011342 1.385062 1.363552 -0.549834 0.688896 1.361288 -0.381137 0.797812 -1.128198 0.369208 0.540132 0.413853 -0.200308 -0.969126 0.981293 -0.009783 -0.320020
8 -0.574816 1.419977 0.434813 -1.101217 -1.586275 1.979573 0.378298 0.782326 2.178987 0.657564 0.683774 -0.091000 -0.059552 -0.738908 -0.907653 -0.701936 0.580039 -0.618757 0.453684 1.665382 -0.152321 0.880077 0.571073 -0.604736 0.532359 0.515031 -0.959844 -0.887184 0.435781 0.862093 -0.956321 -0.625909 0.194472 0.442490 0.526503 -0.215274 0.090711 0.932592 0.811999 -2.497026 0.631545 0.321418 -0.425549 -1.078832 0.753444 0.199790 -0.360526 -0.013448 -0.819476 0.814869 0.442118 -0.972048 -0.060603 -2.349825 1.265445 -0.573257 0.429124 1.049783 1.954773 0.071883 -0.094209 0.265616 0.948318 0.331645 1.343401 -0.167934 -1.105252 -0.167077 -0.096576 -0.838161 -0.208564 0.394534 0.762533 1.235357 -0.207282 -0.202946 -0.468025 0.256944 2.587584 1.186697 -1.031903 1.428316 0.658899 -0.046582 -0.075422 1.329359 -0.684267 -1.524182 2.014061 3.770933 0.647353 -1.021377 -0.345493 0.582811 0.797812 1.326020 1.422857 -3.077007 0.184083 1.478935
9 -0.600142 1.929561 -2.346771 -0.669700 -1.165258 0.814788 0.444449 -0.576758 0.353091 0.408893 0.091391 -2.294389 0.485506 -0.081304 -0.716272 -1.648010 1.005361 -1.489603 0.363098 0.758602 -1.373847 -0.972057 1.988537 0.319829 1.169060 0.146585 1.030388 1.165984 1.369563 0.730984 -1.383696 -0.515189 -0.808927 -1.174651 -1.631502 -1.123414 -0.478155 -1.583067 1.419074 1.668777 1.567517 0.222103 -0.336040 -1.352064 0.251032 -0.401695 0.268413 -0.012299 -0.918953 2.921208 -0.581588 0.672848 1.251136 1.382263 1.429897 1.290990 -1.272673 -0.308611 -0.422988 -0.675642 0.874441 1.305736 -0.262585 -1.099395 -0.667101 -0.646737 -0.556338 -0.196591 0.119306 -0.266455 -0.524267 2.650951 0.097318 -0.974697 0.189964 1.141155 -0.064434 1.104971 -1.508908 -0.031833 0.803919 -0.659221 0.939145 0.214041 -0.531805 0.956060 0.249328 0.637903 -0.510158 1.850287 -0.348407 2.001376 -0.389643 -0.024786 -0.470973 0.869339 0.170667 0.598062 1.217262 1.274013
10 -0.389981 -0.752441 -0.734871 3.517318 -1.173559 -0.004956 0.145419 2.151368 -3.086037 -1.569139 1.449784 -0.868951 -1.687716 -0.994401 1.153266 1.803045 -0.819059 0.847970 0.227102 -0.500762 0.868210 1.823540 1.161007 -0.307606 -0.713416 0.363560 -0.822162 2.427681 -0.129537 -0.078716 1.345644 -1.286094 0.237242 -0.136056 0.596664 -1.412381 1.206341 0.299860 0.705238 0.142412 -1.059382 0.833468 1.060015 -0.527045 -1.135732 -1.140983 -0.779540 -0.640875 -1.217196 -1.675663 0.241263 -0.273322 -1.697936 -0.594943 0.101154 1.391735 -0.426953 1.008344 -0.818577 1.924570 -0.578900 -0.457395 -1.096705 0.418522 -0.155623 0.169706 -2.533706 0.018904 1.434160 0.744095 0.647626 -0.770309 2.329141 -0.141547 -1.761594 0.702091 -1.531450 -0.788427 -0.184622 -1.942321 1.530113 0.503406 1.105845 -0.935120 -1.115483 -2.249762 1.307135 0.788412 -0.441091 0.073561 0.812101 -0.916146 1.573714 -0.309508 0.499987 0.187594 0.558913 0.903246 0.317901 -0.809797
11 1.128248 1.516826 -0.186735 -0.668157 1.132259 -0.246648 -0.855167 0.732283 0.931802 1.318684 -1.198418 -1.149318 0.586321 -1.171937 -0.607731 2.753747 1.479287 -1.136365 -0.020485 0.320444 -1.955755 0.660402 -1.545371 0.200519 -0.017263 1.634686 0.599246 0.462989 0.023721 0.225546 0.170972 -0.027496 -0.061233 -0.566411 -0.669567 0.601618 0.503656 -0.678253 -2.907108 -1.717123 0.397631 1.300108 0.215821 -0.593075 -0.225944 -0.946057 1.000308 0.393160 1.342074 -0.370687 -0.166413 -0.419814 -0.255931 1.789478 0.282378 0.742260 -0.050498 1.415309 0.838166 -1.400292 -0.937976 -1.499148 0.801859 0.224824 0.283572 0.643703 -1.198465 0.527206 0.215202 0.437048 1.312868 0.741243 0.077988 0.006123 0.190370 0.018007 -1.026036 -2.378430 -1.069949 0.843822 1.289216 -1.423369 -0.462887 0.197330 -0.935076 0.441271 0.414643 -0.377887 -0.530515 0.621592 1.009572 0.569718 0.175291 -0.656279 -0.112273 -0.392137 -1.043558 -0.467318 -0.384329 -2.009207
12 0.658598 0.101830 -0.682781 0.229349 -0.305657 0.404877 0.252244 -0.837784 -0.039624 0.329457 0.751694 1.469070 -0.157199 1.032628 -0.584639 -0.925544 0.342474 -0.969363 0.133480 -0.385974 -0.600278 0.281939 0.868579 1.129803 -0.041898 0.961193 0.131521 -0.792889 -1.285737 0.073934 -1.333315 -1.044125 1.277338 1.492257 0.411379 1.771805 -1.111128 1.123233 -1.019449 1.738357 -0.690764 -0.120710 -0.421359 -0.727294 -0.857759 -0.069436 -0.328334 -0.558180 1.063474 -0.519133 -0.496902 1.089589 -1.615801 0.080174 -0.229938 -0.498420 -0.624615 0.059481 -0.093158 -1.784549 -0.503789 -0.140528 0.002653 -0.484930 0.055914 -0.680948 -0.994271 1.277052 0.037651 2.155421 -0.437589 0.696404 0.417752 -0.544785 1.190690 0.978262 0.752102 0.504472 0.139853 -0.505089 -0.264975 -1.603194 0.731847 0.010903 -1.165346 -0.125195 -1.032685 -0.465520 1.514808 0.304762 0.793414 0.314635 -1.638279 0.111737 -0.777037 0.251783 1.126303 -0.808798 0.422064 -0.349264
13 -0.356362 -0.089227 0.609373 0.542382 -0.768681 -0.048074 2.015458 -1.552351 0.251552 1.459635 0.949707 0.339465 -0.001372 1.798589 1.559163 0.231783 0.423141 -0.310530 0.353795 2.173336 -0.196247 -0.375636 -0.858221 0.258410 0.656430 0.960819 1.137893 1.553405 0.038981 -0.632038 -0.132009 -1.834997 -0.242576 -0.297879 -0.441559 -0.769691 0.224077 -0.153009 0.519526 -0.680188 0.535851 0.671496 -0.183064 0.301234 1.288256 -2.478240 -0.360403 0.424067 -0.834659 -0.128464 -0.489013 -0.014888 -1.461230 -1.435223 -1.319802 1.083675 0.979140 -0.375291 1.110189 -1.011351 0.587886 -0.822775 -1.183865 1.455173 1.134328 0.239403 -0.837991 -1.130932 0.783168 1.845520 1.437072 -1.198443 1.379098 2.129113 0.260096 -0.011975 0.043302 0.722941 1.028152 -0.235806 1.145245 -1.359598 0.232189 0.503712 -0.614264 -0.530606 -2.435803 -0.255238 -0.064423 0.784643 0.256346 0.128023 1.414103 -1.118659 0.877353 0.500561 0.463651 -2.034512 -0.981683 -0.691944
14 -1.113376 -1.169402 0.680539 -1.534212 1.653817 -1.295181 -0.566826 0.477014 1.413371 0.517105 1.401153 -0.872685 0.830957 0.181507 -0.145616 0.694592 -0.751208 0.324444 0.681973 -0.054972 0.917776 -1.024810 -0.206446 -0.600113 0.852805 1.455109 -0.079769 0.076076 0.207699 -1.850458 -0.124124 -0.610871 -0.883362 0.219049 -0.685094 -0.645330 -0.242805 -0.775602 0.233070 2.422642 -1.423040 -0.582421 0.968304 -0.701025 -0.167850 0.277264 1.301231 0.301205 -3.081249 -0.562868 0.192944 -0.664592 0.565686 0.190913 -0.841858 -1.856545 -1.022777 1.295968 0.451921 0.659955 0.065818 -0.319586 0.253495 -1.144646 -0.483404 0.555902 0.807069 0.714196 0.661196 0.053667 0.346833 -1.288977 -0.386734 -1.262127 0.477495 -0.494034 -0.911414 1.152963 -0.342365 -0.160187 0.470054 -0.853063 -1.387949 -0.257257 -1.030690 -0.110210 0.328911 -0.555923 0.987713 -0.501957 2.069887 -0.067503 0.316029 -1.506232 2.201621 0.492097 -0.085193 -0.977822 1.039147 -0.653932
15 -0.405638 -1.402027 -1.166242 1.306184 0.856283 -1.236170 -0.646721 -1.474064 0.082960 0.090310 -0.169977 0.406345 0.915427 -0.974503 0.271637 1.539184 -0.098866 -0.525149 1.063933 0.085827 -0.129622 0.947959 -0.072496 -0.237592 0.012549 1.065761 0.996596 -0.172481 2.583139 -0.028578 -0.254856 1.328794 -1.592951 2.434350 -0.341500 -0.307719 -1.333273 -1.100845 0.209097 1.734777 0.639632 0.424779 -0.129327 0.905029 -0.482909 1.731628 -2.783425 -0.333677 -0.110895 1.212636 -0.208412 0.427117 1.348563 0.043859 1.772519 -1.416106 0.401155 0.807157 0.303427 -1.246288 0.178774 -0.066126 -1.862288 1.241295 0.377021 -0.822320 -0.749014 1.463652 1.602268 -1.043877 1.185290 -0.565783 -1.076879 1.360241 -0.121991 0.991043 1.007952 0.450185 -0.744376 1.388876 -0.316847 -0.841655 -1.056842 -0.500226 0.096959 1.176896 -2.939652 1.792213 0.316340 0.303218 1.024967 -0.590871 -0.453326 -0.795981 -0.393301 -0.374372 -1.270199 1.618372 1.197727 -0.914863

还可以粘贴多个指数,甚至只粘贴特定的级别。

[63]:
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])
[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 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 0.228273 1.026890 -0.839585 -0.591182 -0.956888 -0.222326 -0.619915 1.837905 -2.053231 0.868583 -0.920734 -0.232312 2.152957 -1.334661 0.076380 -1.246089 1.202272 -1.049942 1.056610 -0.419678 2.294842 -2.594487 2.822756 0.680889 -1.577693 -1.976254 0.533340 -0.290870 -0.513520 1.982626 0.226001 -1.839905 1.607671 0.388292 0.399732 0.405477 0.217002 -0.633439 0.246622 -1.939546 0.114060 -1.885341 0.243080 -0.705481 0.364628 -0.502952 -0.225752 -0.565538 0.103395 2.018408 1.094248 1.662434 -0.627453 1.621200 1.178133 -0.374879 -0.544329 0.287761 -0.205820 1.189988 0.728927 -0.222040 -1.622706 0.312541 -1.160421 0.313560 0.471998 0.577862 0.505407 -0.626488 -0.346369 -2.065942 0.768936 1.128866 0.166924 -0.967255 0.491996 -0.550857 -0.084694 1.967568 -0.062675 -0.851136 0.426521 -0.277561 -1.377945 -0.095196 0.833639 -0.784754 1.046145 -0.645784 -1.891579 -0.097333 -1.358895 0.498310 -1.147321 -0.536521 -0.916489 -0.212148 0.192844 -0.322683
1 -1.727654 0.764067 0.445314 -2.135576 1.020364 -0.587397 0.048037 0.560169 1.424193 -0.003191 -0.297766 0.232724 0.671954 -1.346282 -0.601723 -0.169196 -0.658381 -0.196024 0.177552 0.032294 1.303258 -0.539484 0.529918 0.382797 1.800623 2.513618 -0.245011 0.208728 -0.300852 0.152992 0.030979 -0.324954 -0.777273 -0.337442 -2.020510 1.419771 -0.741890 -1.559918 0.966290 -0.182294 2.027541 -1.090301 0.430032 -0.730951 0.164135 -0.673210 -0.168668 -0.541845 -0.352464 1.688785 0.092362 1.121011 -0.451224 0.872053 -1.142141 -0.859672 0.930692 -0.177927 -2.158403 -0.289260 -0.904782 0.487616 -0.041970 0.649388 0.019125 -0.977803 -1.972866 -1.266139 -1.000965 -3.049890 0.394720 -1.947339 0.533330 0.379163 2.040071 0.307235 -0.669187 -0.196576 0.922861 1.727249 -0.775059 1.366756 1.693871 -1.282804 -1.932243 -2.063496 -0.395541 1.925655 -0.503716 -1.558305 1.380012 -2.169335 -1.269709 0.905344 0.737179 -1.260360 1.201543 -0.367450 0.878851 0.844085
2 1.351855 1.115809 -1.030206 -0.444282 0.057423 -0.562746 0.004501 0.173643 0.970628 1.867282 0.119880 0.640622 -2.553511 -0.439966 -0.062954 -0.067075 -0.396659 0.405585 -0.749193 -0.653916 -0.167081 1.410437 0.259248 -0.989426 -1.583010 -0.539820 -0.264962 -1.156517 -0.147415 1.063123 0.549318 1.387270 -0.286247 1.573611 0.962956 0.807019 -0.562733 -0.923400 -0.414296 0.003842 -2.096592 -1.858677 -0.968215 0.456882 -0.110648 1.385829 -1.082738 -1.089539 0.595603 0.081374 1.684345 0.305161 0.590335 -0.177260 0.730379 0.147656 -0.150377 0.243728 -0.263203 -0.378285 0.340001 1.544692 0.579486 1.301523 0.085383 -0.826915 0.680524 -1.034403 -1.110716 0.099092 -2.411402 -0.795409 -0.596730 2.016938 0.650740 -0.205659 -1.367066 1.731274 -0.400586 -1.877268 1.997468 0.610815 0.194705 1.178263 0.110523 0.946986 0.157934 1.319965 1.398984 0.049304 -1.106371 -0.376500 2.061808 -1.546407 0.276935 -0.646731 -0.173810 -0.176011 0.289851 0.024213
3 1.329898 -0.251138 -0.892670 -0.886607 0.023848 -2.151303 0.317010 0.936555 -1.793396 0.407319 1.407526 0.669217 -0.063702 -1.134419 0.643766 0.016192 0.584973 0.572833 0.074078 -0.448167 0.032590 -1.096528 0.745444 1.112199 -0.233729 -0.873415 0.230934 -0.805410 0.216766 0.835699 -0.609935 -2.504445 1.268726 0.276230 -0.600436 -1.180951 -0.294444 1.372700 -1.209484 0.178217 0.739316 -0.013644 -1.148450 2.496847 1.112560 0.085375 0.288464 0.359711 -0.547638 1.113638 1.464883 -0.127626 -0.015008 0.467636 -0.544390 0.020004 0.705605 -2.420518 -0.373968 0.467792 -1.684673 -0.616189 3.774140 0.749130 0.888204 -0.307561 0.895529 -0.503150 -2.521870 1.241118 -0.591644 -0.657826 0.890374 0.238272 0.822878 1.866971 0.985183 -0.096968 -0.677218 -0.310448 -0.061652 0.434656 0.113166 -0.122837 -0.003245 -0.188587 0.474867 0.586855 0.721862 0.983135 -0.208411 0.947936 0.067164 -0.100554 1.066966 0.435700 -1.908924 -0.773551 0.580472 -1.620192
1 0 -1.567793 -0.972316 1.536337 -1.046018 0.128710 0.780459 0.558835 -0.402247 -1.785758 1.913771 1.390267 -2.093964 1.585005 0.788355 0.088875 0.453289 0.209618 1.461669 0.164643 0.215340 0.647726 -1.852759 -0.514054 -0.528535 -0.978868 1.563941 0.228150 -1.091756 -0.451212 0.538402 -0.064286 -0.278562 1.297073 0.064941 2.050824 -0.517423 0.456448 -0.021227 0.247564 0.869639 1.539611 0.572745 -0.185547 -0.931420 -1.279881 1.396666 0.552607 1.484888 1.193997 -0.236963 0.350956 1.253611 0.686695 -0.394330 0.549364 -0.742711 -0.465343 1.352667 -0.075703 -2.197694 -0.338980 -0.203617 1.701557 -1.170804 0.747205 0.226150 0.725443 0.611623 0.605679 -0.465381 1.056823 2.836512 -0.126174 -0.286708 -0.311325 -1.959020 0.408000 -1.252445 0.044938 0.066002 -0.778297 -0.304053 -1.400471 -0.355749 -1.671326 0.633932 0.804110 -1.034119 -2.847751 -1.121103 0.430543 -0.971643 -0.706059 -0.416779 1.236913 -0.253807 -0.924209 -0.597519 0.414284 -0.450197
1 -0.773866 -0.240521 -0.217165 1.173609 0.686390 0.008358 0.696232 0.173166 0.620498 0.504067 0.428066 -0.051824 0.719915 0.057165 0.562808 -0.369536 0.483399 0.620765 -0.354342 -1.469471 -1.937266 0.038031 -1.518162 -0.417599 0.386717 0.716193 0.489961 0.733957 0.914415 0.679894 0.255448 -0.508338 0.332030 -0.111107 -0.251983 -1.456620 0.409630 1.062320 -0.577115 0.718796 -0.399260 -1.311389 0.649122 0.091566 0.628872 0.297894 -0.142290 -0.542291 -0.914290 1.144514 0.313584 1.182635 1.214235 -0.416446 -1.653940 -2.550787 0.442473 0.052127 -0.464469 -0.523852 0.989726 -1.325539 -0.199687 -1.226727 0.290018 1.164574 0.817841 -0.309509 0.496599 0.943536 -0.091850 -2.802658 2.126219 -0.521161 0.288098 -0.454663 -1.676143 -0.357661 -0.788960 0.185911 -0.017106 2.454020 1.832706 -0.911743 -0.655873 -0.000514 -2.226997 0.677285 -0.140249 -0.408407 -0.838665 0.482228 1.243458 -0.477394 -0.220343 -2.463966 0.237325 -0.307380 1.172478 0.819492
2 0.405906 -0.978919 1.267526 0.145250 -1.066786 -2.114192 -1.128346 -1.082523 0.372216 0.004127 -0.211984 0.937326 -0.935890 -1.704118 0.611789 -1.030015 0.636123 -1.506193 1.736609 1.392958 1.009424 0.353266 0.697339 -0.297424 0.428702 -0.145346 -0.333553 -0.974699 0.665314 0.971944 0.121950 -1.439668 1.018808 1.442399 -0.199585 -1.165916 0.645656 1.436466 -0.921215 1.293906 -2.706443 1.460928 -0.823197 0.292952 -1.448992 0.026692 -0.975883 0.392823 0.442166 0.745741 1.187982 -0.218570 0.305288 0.054932 -1.476953 -0.114434 0.014103 0.825394 -0.060654 -0.413688 0.974836 1.339210 1.034838 0.040775 0.705001 0.017796 1.867681 -0.390173 2.285277 2.311464 -0.085070 -0.648115 0.576300 -0.790087 -1.183798 -1.334558 -0.454118 0.319302 1.706488 0.830429 0.502476 -0.079631 0.414635 0.332511 0.042935 -0.160910 0.918553 -0.292697 -1.303834 -0.199604 0.871023 -1.370681 -0.205701 -0.492973 1.123083 -0.081842 -0.118527 0.245838 -0.315742 -0.511806
3 0.011470 -0.036104 1.399603 -0.418176 -0.412229 -1.234783 -1.121500 1.196478 -0.569522 0.422022 -0.220484 0.804338 2.892667 -0.511055 -0.168722 -1.477996 -1.969917 0.471354 1.698548 0.137105 -0.762052 0.199379 -0.964346 -0.256692 1.265275 0.848762 -0.784161 1.863776 -0.355569 0.854552 0.768061 -2.075718 -2.501069 1.109868 0.957545 -0.683276 0.307764 0.733073 1.706250 -1.118091 0.374961 -1.414503 -0.524183 -1.662696 0.687921 0.521732 1.451396 -0.833491 -0.362796 -1.174444 -0.813893 -0.893220 0.770743 1.156647 -0.647444 0.125929 0.513600 -0.537874 1.992052 -1.946584 -0.104759 0.484779 -0.290936 -0.441075 0.542993 -1.050038 1.630482 0.239771 -1.177310 0.464804 -0.966995 0.646086 0.486899 1.022196 -2.267827 -1.229616 1.313805 1.073292 2.324940 -0.542720 -1.504292 0.777643 -0.618553 0.011342 1.385062 1.363552 -0.549834 0.688896 1.361288 -0.381137 0.797812 -1.128198 0.369208 0.540132 0.413853 -0.200308 -0.969126 0.981293 -0.009783 -0.320020
B 0 0 -0.574816 1.419977 0.434813 -1.101217 -1.586275 1.979573 0.378298 0.782326 2.178987 0.657564 0.683774 -0.091000 -0.059552 -0.738908 -0.907653 -0.701936 0.580039 -0.618757 0.453684 1.665382 -0.152321 0.880077 0.571073 -0.604736 0.532359 0.515031 -0.959844 -0.887184 0.435781 0.862093 -0.956321 -0.625909 0.194472 0.442490 0.526503 -0.215274 0.090711 0.932592 0.811999 -2.497026 0.631545 0.321418 -0.425549 -1.078832 0.753444 0.199790 -0.360526 -0.013448 -0.819476 0.814869 0.442118 -0.972048 -0.060603 -2.349825 1.265445 -0.573257 0.429124 1.049783 1.954773 0.071883 -0.094209 0.265616 0.948318 0.331645 1.343401 -0.167934 -1.105252 -0.167077 -0.096576 -0.838161 -0.208564 0.394534 0.762533 1.235357 -0.207282 -0.202946 -0.468025 0.256944 2.587584 1.186697 -1.031903 1.428316 0.658899 -0.046582 -0.075422 1.329359 -0.684267 -1.524182 2.014061 3.770933 0.647353 -1.021377 -0.345493 0.582811 0.797812 1.326020 1.422857 -3.077007 0.184083 1.478935
1 -0.600142 1.929561 -2.346771 -0.669700 -1.165258 0.814788 0.444449 -0.576758 0.353091 0.408893 0.091391 -2.294389 0.485506 -0.081304 -0.716272 -1.648010 1.005361 -1.489603 0.363098 0.758602 -1.373847 -0.972057 1.988537 0.319829 1.169060 0.146585 1.030388 1.165984 1.369563 0.730984 -1.383696 -0.515189 -0.808927 -1.174651 -1.631502 -1.123414 -0.478155 -1.583067 1.419074 1.668777 1.567517 0.222103 -0.336040 -1.352064 0.251032 -0.401695 0.268413 -0.012299 -0.918953 2.921208 -0.581588 0.672848 1.251136 1.382263 1.429897 1.290990 -1.272673 -0.308611 -0.422988 -0.675642 0.874441 1.305736 -0.262585 -1.099395 -0.667101 -0.646737 -0.556338 -0.196591 0.119306 -0.266455 -0.524267 2.650951 0.097318 -0.974697 0.189964 1.141155 -0.064434 1.104971 -1.508908 -0.031833 0.803919 -0.659221 0.939145 0.214041 -0.531805 0.956060 0.249328 0.637903 -0.510158 1.850287 -0.348407 2.001376 -0.389643 -0.024786 -0.470973 0.869339 0.170667 0.598062 1.217262 1.274013
2 -0.389981 -0.752441 -0.734871 3.517318 -1.173559 -0.004956 0.145419 2.151368 -3.086037 -1.569139 1.449784 -0.868951 -1.687716 -0.994401 1.153266 1.803045 -0.819059 0.847970 0.227102 -0.500762 0.868210 1.823540 1.161007 -0.307606 -0.713416 0.363560 -0.822162 2.427681 -0.129537 -0.078716 1.345644 -1.286094 0.237242 -0.136056 0.596664 -1.412381 1.206341 0.299860 0.705238 0.142412 -1.059382 0.833468 1.060015 -0.527045 -1.135732 -1.140983 -0.779540 -0.640875 -1.217196 -1.675663 0.241263 -0.273322 -1.697936 -0.594943 0.101154 1.391735 -0.426953 1.008344 -0.818577 1.924570 -0.578900 -0.457395 -1.096705 0.418522 -0.155623 0.169706 -2.533706 0.018904 1.434160 0.744095 0.647626 -0.770309 2.329141 -0.141547 -1.761594 0.702091 -1.531450 -0.788427 -0.184622 -1.942321 1.530113 0.503406 1.105845 -0.935120 -1.115483 -2.249762 1.307135 0.788412 -0.441091 0.073561 0.812101 -0.916146 1.573714 -0.309508 0.499987 0.187594 0.558913 0.903246 0.317901 -0.809797
3 1.128248 1.516826 -0.186735 -0.668157 1.132259 -0.246648 -0.855167 0.732283 0.931802 1.318684 -1.198418 -1.149318 0.586321 -1.171937 -0.607731 2.753747 1.479287 -1.136365 -0.020485 0.320444 -1.955755 0.660402 -1.545371 0.200519 -0.017263 1.634686 0.599246 0.462989 0.023721 0.225546 0.170972 -0.027496 -0.061233 -0.566411 -0.669567 0.601618 0.503656 -0.678253 -2.907108 -1.717123 0.397631 1.300108 0.215821 -0.593075 -0.225944 -0.946057 1.000308 0.393160 1.342074 -0.370687 -0.166413 -0.419814 -0.255931 1.789478 0.282378 0.742260 -0.050498 1.415309 0.838166 -1.400292 -0.937976 -1.499148 0.801859 0.224824 0.283572 0.643703 -1.198465 0.527206 0.215202 0.437048 1.312868 0.741243 0.077988 0.006123 0.190370 0.018007 -1.026036 -2.378430 -1.069949 0.843822 1.289216 -1.423369 -0.462887 0.197330 -0.935076 0.441271 0.414643 -0.377887 -0.530515 0.621592 1.009572 0.569718 0.175291 -0.656279 -0.112273 -0.392137 -1.043558 -0.467318 -0.384329 -2.009207
1 0 0.658598 0.101830 -0.682781 0.229349 -0.305657 0.404877 0.252244 -0.837784 -0.039624 0.329457 0.751694 1.469070 -0.157199 1.032628 -0.584639 -0.925544 0.342474 -0.969363 0.133480 -0.385974 -0.600278 0.281939 0.868579 1.129803 -0.041898 0.961193 0.131521 -0.792889 -1.285737 0.073934 -1.333315 -1.044125 1.277338 1.492257 0.411379 1.771805 -1.111128 1.123233 -1.019449 1.738357 -0.690764 -0.120710 -0.421359 -0.727294 -0.857759 -0.069436 -0.328334 -0.558180 1.063474 -0.519133 -0.496902 1.089589 -1.615801 0.080174 -0.229938 -0.498420 -0.624615 0.059481 -0.093158 -1.784549 -0.503789 -0.140528 0.002653 -0.484930 0.055914 -0.680948 -0.994271 1.277052 0.037651 2.155421 -0.437589 0.696404 0.417752 -0.544785 1.190690 0.978262 0.752102 0.504472 0.139853 -0.505089 -0.264975 -1.603194 0.731847 0.010903 -1.165346 -0.125195 -1.032685 -0.465520 1.514808 0.304762 0.793414 0.314635 -1.638279 0.111737 -0.777037 0.251783 1.126303 -0.808798 0.422064 -0.349264
1 -0.356362 -0.089227 0.609373 0.542382 -0.768681 -0.048074 2.015458 -1.552351 0.251552 1.459635 0.949707 0.339465 -0.001372 1.798589 1.559163 0.231783 0.423141 -0.310530 0.353795 2.173336 -0.196247 -0.375636 -0.858221 0.258410 0.656430 0.960819 1.137893 1.553405 0.038981 -0.632038 -0.132009 -1.834997 -0.242576 -0.297879 -0.441559 -0.769691 0.224077 -0.153009 0.519526 -0.680188 0.535851 0.671496 -0.183064 0.301234 1.288256 -2.478240 -0.360403 0.424067 -0.834659 -0.128464 -0.489013 -0.014888 -1.461230 -1.435223 -1.319802 1.083675 0.979140 -0.375291 1.110189 -1.011351 0.587886 -0.822775 -1.183865 1.455173 1.134328 0.239403 -0.837991 -1.130932 0.783168 1.845520 1.437072 -1.198443 1.379098 2.129113 0.260096 -0.011975 0.043302 0.722941 1.028152 -0.235806 1.145245 -1.359598 0.232189 0.503712 -0.614264 -0.530606 -2.435803 -0.255238 -0.064423 0.784643 0.256346 0.128023 1.414103 -1.118659 0.877353 0.500561 0.463651 -2.034512 -0.981683 -0.691944
2 -1.113376 -1.169402 0.680539 -1.534212 1.653817 -1.295181 -0.566826 0.477014 1.413371 0.517105 1.401153 -0.872685 0.830957 0.181507 -0.145616 0.694592 -0.751208 0.324444 0.681973 -0.054972 0.917776 -1.024810 -0.206446 -0.600113 0.852805 1.455109 -0.079769 0.076076 0.207699 -1.850458 -0.124124 -0.610871 -0.883362 0.219049 -0.685094 -0.645330 -0.242805 -0.775602 0.233070 2.422642 -1.423040 -0.582421 0.968304 -0.701025 -0.167850 0.277264 1.301231 0.301205 -3.081249 -0.562868 0.192944 -0.664592 0.565686 0.190913 -0.841858 -1.856545 -1.022777 1.295968 0.451921 0.659955 0.065818 -0.319586 0.253495 -1.144646 -0.483404 0.555902 0.807069 0.714196 0.661196 0.053667 0.346833 -1.288977 -0.386734 -1.262127 0.477495 -0.494034 -0.911414 1.152963 -0.342365 -0.160187 0.470054 -0.853063 -1.387949 -0.257257 -1.030690 -0.110210 0.328911 -0.555923 0.987713 -0.501957 2.069887 -0.067503 0.316029 -1.506232 2.201621 0.492097 -0.085193 -0.977822 1.039147 -0.653932
3 -0.405638 -1.402027 -1.166242 1.306184 0.856283 -1.236170 -0.646721 -1.474064 0.082960 0.090310 -0.169977 0.406345 0.915427 -0.974503 0.271637 1.539184 -0.098866 -0.525149 1.063933 0.085827 -0.129622 0.947959 -0.072496 -0.237592 0.012549 1.065761 0.996596 -0.172481 2.583139 -0.028578 -0.254856 1.328794 -1.592951 2.434350 -0.341500 -0.307719 -1.333273 -1.100845 0.209097 1.734777 0.639632 0.424779 -0.129327 0.905029 -0.482909 1.731628 -2.783425 -0.333677 -0.110895 1.212636 -0.208412 0.427117 1.348563 0.043859 1.772519 -1.416106 0.401155 0.807157 0.303427 -1.246288 0.178774 -0.066126 -1.862288 1.241295 0.377021 -0.822320 -0.749014 1.463652 1.602268 -1.043877 1.185290 -0.565783 -1.076879 1.360241 -0.121991 0.991043 1.007952 0.450185 -0.744376 1.388876 -0.316847 -0.841655 -1.056842 -0.500226 0.096959 1.176896 -2.939652 1.792213 0.316340 0.303218 1.024967 -0.590871 -0.453326 -0.795981 -0.393301 -0.374372 -1.270199 1.618372 1.197727 -0.914863

超文本标记语言转义#

假设你必须在超文本标记语言中显示超文本标记语言,当呈现器不能区分时,这可能有点麻烦。您可以使用 escape 格式化选项来处理这一问题,甚至在包含HTML本身的格式化程序中使用它。

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

导出到Excel#

一些支持( 从版本0.20.0开始 )可用于导出样式 DataFrames 到Excel工作表,使用 OpenPyXLXlsxWriter 引擎。处理的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-style and border-left-style) as well as the border shorthands for all sides (border: 1px solid green) or specified sides (border-left: 1px solid green). Using a border shorthand will override any border properties set before it (See CSS Working Group 了解更多详细信息)

  • 仅CSS2表单的命名颜色和十六进制颜色 #rgb#rrggbb 目前均受支持。

  • 还可以使用以下伪css属性来设置特定于Excel的样式属性:

    • number-format

导出到Excel中不包括表级样式和数据单元格css类:单个单元格的属性必须由 Styler.apply 和/或 Styler.applymap 方法。

[67]:
df2.style.\
    applymap(style_negative, props='color:red;').\
    highlight_max(axis=0).\
    to_excel('styled.xlsx', engine='openpyxl')
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Input In [67], in <cell line: 1>()
----> 1 df2.style.\
      2     applymap(style_negative, props='color:red;').\
      3     highlight_max(axis=0).\
      4     to_excel('styled.xlsx', engine='openpyxl')

File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/io/formats/style.py:584, in Styler.to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, verbose, freeze_panes)
    571 from pandas.io.formats.excel import ExcelFormatter
    573 formatter = ExcelFormatter(
    574     self,
    575     na_rep=na_rep,
   (...)
    582     inf_rep=inf_rep,
    583 )
--> 584 formatter.write(
    585     excel_writer,
    586     sheet_name=sheet_name,
    587     startrow=startrow,
    588     startcol=startcol,
    589     freeze_panes=freeze_panes,
    590     engine=engine,
    591 )

File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/io/formats/excel.py:896, in ExcelFormatter.write(self, writer, sheet_name, startrow, startcol, freeze_panes, engine, storage_options)
    892     need_save = False
    893 else:
    894     # error: Cannot instantiate abstract class 'ExcelWriter' with abstract
    895     # attributes 'engine', 'save', 'supported_extensions' and 'write_cells'
--> 896     writer = ExcelWriter(  # type: ignore[abstract]
    897         writer, engine=engine, storage_options=storage_options
    898     )
    899     need_save = True
    901 try:

File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/io/excel/_openpyxl.py:55, in OpenpyxlWriter.__init__(self, path, engine, date_format, datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs, **kwargs)
     42 def __init__(
     43     self,
     44     path: FilePath | WriteExcelBuffer | ExcelWriter,
   (...)
     53 ) -> None:
     54     # Use the openpyxl module as the Excel writer.
---> 55     from openpyxl.workbook import Workbook
     57     engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
     59     super().__init__(
     60         path,
     61         mode=mode,
   (...)
     64         engine_kwargs=engine_kwargs,
     65     )

ModuleNotFoundError: No module named 'openpyxl'

输出的屏幕截图:

带有样式DataFrame的Excel电子表格

导出到LaTeX#

有支持( 从1.3.0版开始 )出口 Styler to LaTeX. The documentation for the .to_latex 方法给出了更多的细节和大量的例子。

有关css和html的更多信息#

层叠样式表(Cascading Style Sheet,CSS)语言是为了影响浏览器呈现HTML元素的方式而设计的,它有自己的特点。它从不报告错误:它只是默默地忽略它们,并且不会按照您希望的方式呈现您的对象,因此有时可能会令人沮丧。下面是一个非常简短的入门读物 Styler 创建html并与css交互,并提供要避免的常见陷阱建议。

Css类和ID#

Css的精确结构 class 附着到每个单元格如下所示。

  • 具有索引和列名的单元格包括 index_namelevel<k> 哪里 k 它的级别是否在多索引中

  • 索引标签单元格包括

    • row_heading

    • level<k> 哪里 k 是多重索引中的级别

    • row<m> 哪里 m 是行的数字位置。

  • 列标签单元格包括

    • col_heading

    • level<k> 哪里 k 是多重索引中的级别

    • col<n> 哪里 n 是列的数字位置

  • 数据单元格包括

    • data

    • row<m> ,在哪里 m 是单元格的数字位置。

    • col<n> ,在哪里 n 是单元格的数字位置。

  • 空白单元格包括 blank

  • 修剪后的单元格包括 col_trimrow_trim

的结构。 id is T_uuid_level<k>_row<m>_col<n> where level<k> is used only on headings, and headings will only have either row<m> or col<n> whichever is needed. By default we’ve also prepended each row/column identifier with a UUID unique to each DataFrame so that the style from one doesn’t collide with the styling from another within the same notebook or page. You can read more about the use of UUIDs in Optimization

我们可以通过调用 .to_html() 方法。

[68]:
print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.to_html())
<style type="text/css">
</style>
<table id="T_cc0d3">
  <thead>
    <tr>
      <th class="blank level0" >&nbsp;</th>
      <th id="T_cc0d3_level0_col0" class="col_heading level0 col0" >c1</th>
      <th id="T_cc0d3_level0_col1" class="col_heading level0 col1" >c2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_cc0d3_level0_row0" class="row_heading level0 row0" >i1</th>
      <td id="T_cc0d3_row0_col0" class="data row0 col0" >1</td>
      <td id="T_cc0d3_row0_col1" class="data row0 col1" >2</td>
    </tr>
    <tr>
      <th id="T_cc0d3_level0_row1" class="row_heading level0 row1" >i2</th>
      <td id="T_cc0d3_row1_col0" class="data row1 col0" >3</td>
      <td id="T_cc0d3_row1_col1" class="data row1 col1" >4</td>
    </tr>
  </tbody>
</table>

Css层次结构#

这些示例表明,当CSS样式重叠时,在HTML呈现中最后出现的样式优先。因此,以下结果会产生不同的结果:

[69]:
df4 = pd.DataFrame([['text']])
df4.style.applymap(lambda x: 'color:green;')\
         .applymap(lambda x: 'color:red;')
[69]:
  0
0 text
[70]:
df4.style.applymap(lambda x: 'color:red;')\
         .applymap(lambda x: 'color:green;')
[70]:
  0
0 text

这仅适用于在层次结构或重要性上相同的CSS规则。你可以读到更多关于 CSS specificity here 但就我们的目的而言,总结一下关键点就足够了:

通过从零开始并添加以下内容,可以得出每个HTML元素的CSS重要性分数:

  • 内联样式属性为1000

  • 每个ID为100

  • 每个属性、类或伪类10

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

让我们用它来描述以下配置的操作

[71]:
df4.style.set_uuid('a_')\
         .set_table_styles([{'selector': 'td', 'props': 'color:red;'}])\
         .applymap(lambda x: 'color:green;')
[71]:
  0
0 text

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

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

在上面的例子中,文本是蓝色的,因为选择符 #T_b_ .cls-1 价值110(ID加职业),这需要优先。

[73]:
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;'}])\
         .applymap(lambda x: 'color:green;')\
         .set_td_classes(pd.DataFrame([['cls-1']]))
[73]:
  0
0 text

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

如果你的风格没有被应用,而且真的很令人沮丧,那就试试 !important 特朗普牌。

[74]:
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;'}])\
         .applymap(lambda x: 'color:green !important;')\
         .set_td_classes(pd.DataFrame([['cls-1']]))
[74]:
  0
0 text

终于收到那条绿色短信了!

可扩展性#

Pandas的核心是,并将继续保持其“高性能、易用的数据结构”。考虑到这一点,我们希望 DataFrame.style 实现两个目标

  • 提供一个令人愉快的交互使用的API,并且对于许多任务来说是“足够好的”

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

如果您在此基础上构建了一个伟大的类库,请让我们知道,我们将 link 为它干杯。

子类化#

如果默认模板不太符合您的需要,您可以子类化Styler并扩展或覆盖模板。我们将展示一个扩展默认模板的示例,以便在每个表之前插入一个定制标题。

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

我们将使用以下模板:

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

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

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

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

现在我们可以使用该定制样式器了。它是 __init__ 获取DataFrame。

[78]:
MyStyler(df3)
[78]:

My Table

    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

我们的自定义模板接受 table_title 关键词。我们可以在 .to_html 方法。

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

Extending Example

    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

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

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

Another Title

    c1 c2 c3 c4
A r1 -1.048553 -1.420018 -1.706270 1.950775
r2 -0.509652 -0.438074 -1.252795 0.777490
B r1 -1.613898 -0.212740 -0.895467 0.386902
r2 -0.510805 -1.180632 -0.028182 0.428332

模板结构#

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

样式模板:

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

表格模板:

[84]:
HTML(table_structure)
[84]:
before_table
table
<table ...>
caption
thead
before_head_rows
head_tr (loop over headers)
after_head_rows
tbody
before_rows
tr (loop over data rows)
after_rows
</table>
after_table

请参阅 GitHub repo 了解更多详细信息。