Pandas-2-2-中文文档-十一-
Pandas 2.2 中文文档(十一)
可空整数数据类型
注意
IntegerArray 目前处于实验阶段。其 API 或实现可能会在没有警告的情况下发生变化。使用pandas.NA
作为缺失值。
在处理缺失数据中,我们看到 pandas 主要使用NaN
来表示缺失数据。因为NaN
是一个浮点数,这会导致任何带有缺失值的整数数组变为浮点数。在某些情况下,这可能并不重要。但是,如果您的整数列是标识符,转换为浮点数可能会有问题。有些整数甚至无法表示为浮点数。
构造
pandas 可以使用arrays.IntegerArray
来表示可能存在缺失值的整数数据。这是 pandas 内部实现的一种扩展类型。
In [1]: arr = pd.array([1, 2, None], dtype=pd.Int64Dtype())
In [2]: arr
Out[2]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
或者字符串别名"Int64"
(注意大写的"I"
)以区别于 NumPy 的'int64'
dtype:
In [3]: pd.array([1, 2, np.nan], dtype="Int64")
Out[3]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
所有类似 NA 的值都被替换为pandas.NA
。
In [4]: pd.array([1, 2, np.nan, None, pd.NA], dtype="Int64")
Out[4]:
<IntegerArray>
[1, 2, <NA>, <NA>, <NA>]
Length: 5, dtype: Int64
这个数组可以像任何 NumPy 数组一样存储在DataFrame
或Series
中。
In [5]: pd.Series(arr)
Out[5]:
0 1
1 2
2 <NA>
dtype: Int64
您还可以将类似列表的对象传递给带有 dtype 的Series
构造函数。
警告
目前pandas.array()
和pandas.Series()
在 dtype 推断上使用不同规则。pandas.array()
将推断出一个可空整数 dtype。
In [6]: pd.array([1, None])
Out[6]:
<IntegerArray>
[1, <NA>]
Length: 2, dtype: Int64
In [7]: pd.array([1, 2])
Out[7]:
<IntegerArray>
[1, 2]
Length: 2, dtype: Int64
为了向后兼容,Series
将这些推断为整数或浮点 dtype。
In [8]: pd.Series([1, None])
Out[8]:
0 1.0
1 NaN
dtype: float64
In [9]: pd.Series([1, 2])
Out[9]:
0 1
1 2
dtype: int64
我们建议明确提供 dtype 以避免混淆。
In [10]: pd.array([1, None], dtype="Int64")
Out[10]:
<IntegerArray>
[1, <NA>]
Length: 2, dtype: Int64
In [11]: pd.Series([1, None], dtype="Int64")
Out[11]:
0 1
1 <NA>
dtype: Int64
在将来,我们可能会提供一个选项,使Series
能够推断出一个可空整数 dtype。
操作
涉及整数数组的操作将类似于 NumPy 数组。缺失值将被传播,并且数据将根据需要强制转换为另一个 dtype。
In [12]: s = pd.Series([1, 2, None], dtype="Int64")
# arithmetic
In [13]: s + 1
Out[13]:
0 2
1 3
2 <NA>
dtype: Int64
# comparison
In [14]: s == 1
Out[14]:
0 True
1 False
2 <NA>
dtype: boolean
# slicing operation
In [15]: s.iloc[1:3]
Out[15]:
1 2
2 <NA>
dtype: Int64
# operate with other dtypes
In [16]: s + s.iloc[1:3].astype("Int8")
Out[16]:
0 <NA>
1 4
2 <NA>
dtype: Int64
# coerce when needed
In [17]: s + 0.01
Out[17]:
0 1.01
1 2.01
2 <NA>
dtype: Float64
这些 dtype 可以作为DataFrame
的一部分运行。
In [18]: df = pd.DataFrame({"A": s, "B": [1, 1, 3], "C": list("aab")})
In [19]: df
Out[19]:
A B C
0 1 1 a
1 2 1 a
2 <NA> 3 b
In [20]: df.dtypes
Out[20]:
A Int64
B int64
C object
dtype: object
这些 dtype 可以合并、重塑和转换。
In [21]: pd.concat([df[["A"]], df[["B", "C"]]], axis=1).dtypes
Out[21]:
A Int64
B int64
C object
dtype: object
In [22]: df["A"].astype(float)
Out[22]:
0 1.0
1 2.0
2 NaN
Name: A, dtype: float64
诸如sum()
之类的缩减和分组操作同样有效。
In [23]: df.sum(numeric_only=True)
Out[23]:
A 3
B 5
dtype: Int64
In [24]: df.sum()
Out[24]:
A 3
B 5
C aab
dtype: object
In [25]: df.groupby("B").A.sum()
Out[25]:
B
1 3
3 0
Name: A, dtype: Int64
标量 NA 值
arrays.IntegerArray
使用pandas.NA
作为其标量缺失值。切片一个缺失的单个元素将返回pandas.NA
In [26]: a = pd.array([1, None], dtype="Int64")
In [27]: a[1]
Out[27]: <NA>
构造
pandas 可以使用arrays.IntegerArray
表示可能包含缺失值的整数数据。这是 pandas 内部实现的一种扩展类型。
In [1]: arr = pd.array([1, 2, None], dtype=pd.Int64Dtype())
In [2]: arr
Out[2]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
或者字符串别名"Int64"
(注意大写的"I"
)以区别于 NumPy 的'int64'
数据类型:
In [3]: pd.array([1, 2, np.nan], dtype="Int64")
Out[3]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
所有类似 NA 的值都将被替换为pandas.NA
。
In [4]: pd.array([1, 2, np.nan, None, pd.NA], dtype="Int64")
Out[4]:
<IntegerArray>
[1, 2, <NA>, <NA>, <NA>]
Length: 5, dtype: Int64
这个数组可以像任何 NumPy 数组一样存储在DataFrame
或Series
中。
In [5]: pd.Series(arr)
Out[5]:
0 1
1 2
2 <NA>
dtype: Int64
您还可以将类似列表的对象传递给带有数据类型的Series
构造函数。
警告
目前pandas.array()
和pandas.Series()
使用不同的规则进行数据类型推断。pandas.array()
将推断为可空整数数据类型
In [6]: pd.array([1, None])
Out[6]:
<IntegerArray>
[1, <NA>]
Length: 2, dtype: Int64
In [7]: pd.array([1, 2])
Out[7]:
<IntegerArray>
[1, 2]
Length: 2, dtype: Int64
为了向后兼容,Series
将这些推断为整数或浮点数数据类型。
In [8]: pd.Series([1, None])
Out[8]:
0 1.0
1 NaN
dtype: float64
In [9]: pd.Series([1, 2])
Out[9]:
0 1
1 2
dtype: int64
我们建议明确提供数据类型以避免混淆。
In [10]: pd.array([1, None], dtype="Int64")
Out[10]:
<IntegerArray>
[1, <NA>]
Length: 2, dtype: Int64
In [11]: pd.Series([1, None], dtype="Int64")
Out[11]:
0 1
1 <NA>
dtype: Int64
将来,我们可能会提供一个选项,使Series
推断为可空整数数据类型。
操作
涉及整数数组的操作将类似于 NumPy 数组。缺失值将被传播,并且数据将根据需要强制转换为另一种数据类型。
In [12]: s = pd.Series([1, 2, None], dtype="Int64")
# arithmetic
In [13]: s + 1
Out[13]:
0 2
1 3
2 <NA>
dtype: Int64
# comparison
In [14]: s == 1
Out[14]:
0 True
1 False
2 <NA>
dtype: boolean
# slicing operation
In [15]: s.iloc[1:3]
Out[15]:
1 2
2 <NA>
dtype: Int64
# operate with other dtypes
In [16]: s + s.iloc[1:3].astype("Int8")
Out[16]:
0 <NA>
1 4
2 <NA>
dtype: Int64
# coerce when needed
In [17]: s + 0.01
Out[17]:
0 1.01
1 2.01
2 <NA>
dtype: Float64
这些数据类型可以作为DataFrame
的一部分操作。
In [18]: df = pd.DataFrame({"A": s, "B": [1, 1, 3], "C": list("aab")})
In [19]: df
Out[19]:
A B C
0 1 1 a
1 2 1 a
2 <NA> 3 b
In [20]: df.dtypes
Out[20]:
A Int64
B int64
C object
dtype: object
这些数据类型可以合并、重塑和转换。
In [21]: pd.concat([df[["A"]], df[["B", "C"]]], axis=1).dtypes
Out[21]:
A Int64
B int64
C object
dtype: object
In [22]: df["A"].astype(float)
Out[22]:
0 1.0
1 2.0
2 NaN
Name: A, dtype: float64
缩减和分组操作,如sum()
同样有效。
In [23]: df.sum(numeric_only=True)
Out[23]:
A 3
B 5
dtype: Int64
In [24]: df.sum()
Out[24]:
A 3
B 5
C aab
dtype: object
In [25]: df.groupby("B").A.sum()
Out[25]:
B
1 3
3 0
Name: A, dtype: Int64
标量 NA 值
arrays.IntegerArray
使用pandas.NA
作为其标量缺失值。切片一个缺失的单个元素将返回pandas.NA
In [26]: a = pd.array([1, None], dtype="Int64")
In [27]: a[1]
Out[27]: <NA>
可空布尔数据类型
注意
BooleanArray 目前处于实验阶段。其 API 或实现可能会在没有警告的情况下更改。
使用 NA 值进行索引
pandas 允许在布尔数组中使用NA
值进行索引,这些值被视为False
。
In [1]: s = pd.Series([1, 2, 3])
In [2]: mask = pd.array([True, False, pd.NA], dtype="boolean")
In [3]: s[mask]
Out[3]:
0 1
dtype: int64
如果您希望保留NA
值,可以手动用fillna(True)
填充它们。
In [4]: s[mask.fillna(True)]
Out[4]:
0 1
2 3
dtype: int64
``` ## Kleene 逻辑操作
`arrays.BooleanArray`实现了[Kleene 逻辑](https://en.wikipedia.org/wiki/Three-valued_logic#Kleene_and_Priest_logics)(有时称为三值逻辑)用于逻辑操作,如`&`(与)、`|`(或)和`^`(异或)。
这个表格展示了每种组合的结果。这些操作是对称的,因此左右两侧的翻转不会影响结果。
| 表达式 | 结果 |
| --- | --- |
| `True & True` | `True` |
| `True & False` | `False` |
| `True & NA` | `NA` |
| `False & False` | `False` |
| `False & NA` | `False` |
| `NA & NA` | `NA` |
| `True | True` | `True` |
| `True | False` | `True` |
| `True | NA` | `True` |
| `False | False` | `False` |
| `False | NA` | `NA` |
| `NA | NA` | `NA` |
| `True ^ True` | `False` |
| `True ^ False` | `True` |
| `True ^ NA` | `NA` |
| `False ^ False` | `False` |
| `False ^ NA` | `NA` |
| `NA ^ NA` | `NA` |
当操作中存在`NA`时,输出值仅在无法仅根据其他输入确定结果时为`NA`。例如,`True | NA`是`True`,因为`True | True`和`True | False`都是`True`。在这种情况下,我们实际上不需要考虑`NA`的值。
另一方面,`True & NA`是`NA`。结果取决于`NA`是真是假,因为`True & True`是`True`,但`True & False`是`False`,所以我们无法确定输出。
这与`np.nan`在逻辑操作中的行为不同。pandas 将`np.nan`视为*输出中始终为假*。
在`or`中
```py
In [5]: pd.Series([True, False, np.nan], dtype="object") | True
Out[5]:
0 True
1 True
2 False
dtype: bool
In [6]: pd.Series([True, False, np.nan], dtype="boolean") | True
Out[6]:
0 True
1 True
2 True
dtype: boolean
在and
中
In [7]: pd.Series([True, False, np.nan], dtype="object") & True
Out[7]:
0 True
1 False
2 False
dtype: bool
In [8]: pd.Series([True, False, np.nan], dtype="boolean") & True
Out[8]:
0 True
1 False
2 <NA>
dtype: boolean
``` ## 使用 NA 值进行索引
pandas 允许在布尔数组中使用`NA`值进行索引,这些值被视为`False`。
```py
In [1]: s = pd.Series([1, 2, 3])
In [2]: mask = pd.array([True, False, pd.NA], dtype="boolean")
In [3]: s[mask]
Out[3]:
0 1
dtype: int64
如果您希望保留NA
值,可以手动用fillna(True)
填充它们。
In [4]: s[mask.fillna(True)]
Out[4]:
0 1
2 3
dtype: int64
Kleene 逻辑操作
arrays.BooleanArray
实现了Kleene 逻辑(有时称为三值逻辑)用于逻辑操作,如&
(与)、|
(或)和^
(异或)。
这个表格展示了每种组合的结果。这些操作是对称的,因此左右两侧的翻转不会影响结果。
表达式 | 结果 |
---|---|
True & True |
True |
True & False |
False |
True & NA |
NA |
False & False |
False |
False & NA |
False |
NA & NA |
NA |
True | True |
True |
True | False |
True |
True | NA |
True |
False | False |
False |
False | NA |
NA |
NA | NA |
NA |
True ^ True |
False |
True ^ False |
True |
True ^ NA |
NA |
False ^ False |
False |
False ^ NA |
NA |
NA ^ NA |
NA |
当操作中存在NA
时,仅当结果无法仅基于其他输入确定时,输出值才为NA
。例如,True | NA
为True
,因为True | True
和True | False
都为True
。在这种情况下,我们实际上不需要考虑NA
的值。
另一方面,True & NA
为NA
。结果取决于NA
是否真的为True
或False
,因为True & True
为True
,但True & False
为False
,所以我们无法确定输出。
这与np.nan
在逻辑操作中的行为不同。pandas 将np.nan
视为输出中始终为假。
在or
中
In [5]: pd.Series([True, False, np.nan], dtype="object") | True
Out[5]:
0 True
1 True
2 False
dtype: bool
In [6]: pd.Series([True, False, np.nan], dtype="boolean") | True
Out[6]:
0 True
1 True
2 True
dtype: boolean
在and
中
In [7]: pd.Series([True, False, np.nan], dtype="object") & True
Out[7]:
0 True
1 False
2 False
dtype: bool
In [8]: pd.Series([True, False, np.nan], dtype="boolean") & True
Out[8]:
0 True
1 False
2 <NA>
dtype: boolean
图表可视化
注意
下面的示例假定您正在使用Jupyter。
本节演示了通过图表进行可视化。 有关表格数据可视化的信息,请参阅表格可视化部分。
我们使用标准约定引用 matplotlib API:
In [1]: import matplotlib.pyplot as plt
In [2]: plt.close("all")
我们在 pandas 中提供了基础知识,以轻松创建看起来不错的图形。 请参阅生态系统页面 以了解超越此处基础文档的可视化库。
注意
所有对 np.random
的调用都使用 123456 作为种子。
基本绘图:plot
我们将演示基础知识,有关一些高级策略,请参阅食谱。
Series 和 DataFrame 上的 plot
方法只是 plt.plot()
的简单包装:
In [3]: np.random.seed(123456)
In [4]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [5]: ts = ts.cumsum()
In [6]: ts.plot();
如果索引由日期组成,则调用gcf().autofmt_xdate()
尝试根据上述格式化 x 轴。
在 DataFrame 上,plot()
是一个方便的方法,用于绘制所有带有标签的列:
In [7]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [8]: df = df.cumsum()
In [9]: plt.figure();
In [10]: df.plot();
您可以使用 plot()
中的 x
和 y
关键字绘制一列与另一列的图形:
In [11]: df3 = pd.DataFrame(np.random.randn(1000, 2), columns=["B", "C"]).cumsum()
In [12]: df3["A"] = pd.Series(list(range(len(df))))
In [13]: df3.plot(x="A", y="B");
注意
要了解更多格式和样式选项,请参阅下面的格式化。 ## 其他绘图
绘图方法允许使用除默认线图之外的几种绘图样式。 这些方法可以作为 plot()
的 kind
关键字参数提供,包括:
-
‘bar’ 或 ‘barh’ 用于条形图
-
‘hist’ 用于直方图
-
‘box’ 用于箱线图
-
‘kde’ 或 ‘density’ 用于密度图
-
‘area’ 用于面积图
-
‘scatter’ 用于散点图
-
‘hexbin’ 用于六边形箱图
-
‘pie’ 用于饼图
例如,可以通过以下方式创建条形图:
In [14]: plt.figure();
In [15]: df.iloc[5].plot(kind="bar");
您还可以使用方法DataFrame.plot.<kind>
创建其他图表,而不是提供kind
关键字参数。这样更容易发现绘图方法及其使用的特定参数:
In [16]: df = pd.DataFrame()
In [17]: df.plot.<TAB> # noqa: E225, E999
df.plot.area df.plot.barh df.plot.density df.plot.hist df.plot.line df.plot.scatter
df.plot.bar df.plot.box df.plot.hexbin df.plot.kde df.plot.pie
除了这些kind
,��有 DataFrame.hist()和 DataFrame.boxplot()方法,它们使用单独的接口。
最后,在pandas.plotting
中有几个绘图函数,它们以Series
或DataFrame
作为参数。这些包括:
-
散点矩阵
-
安德鲁斯曲线
-
平行坐标
-
滞后图
-
自相关图
-
自举图
-
RadViz
图表也可以用误差条或表格装饰。
条形图
对于带标签的非时间序列数据,您可能希望生成条形图:
In [18]: plt.figure();
In [19]: df.iloc[5].plot.bar();
In [20]: plt.axhline(0, color="k");
调用 DataFrame 的plot.bar()
方法会生成多条形图:
In [21]: df2 = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
In [22]: df2.plot.bar();
要生成堆叠条形图,请传递stacked=True
:
In [23]: df2.plot.bar(stacked=True);
要获得水平条形图,请使用barh
方法:
In [24]: df2.plot.barh(stacked=True);
### 直方图
可以使用DataFrame.plot.hist()
和Series.plot.hist()
方法绘制直方图。
In [25]: df4 = pd.DataFrame(
....: {
....: "a": np.random.randn(1000) + 1,
....: "b": np.random.randn(1000),
....: "c": np.random.randn(1000) - 1,
....: },
....: columns=["a", "b", "c"],
....: )
....:
In [26]: plt.figure();
In [27]: df4.plot.hist(alpha=0.5);
使用stacked=True
可以堆叠直方图。可以使用bins
关键字更改箱子大小。
In [28]: plt.figure();
In [29]: df4.plot.hist(stacked=True, bins=20);
您可以传递 matplotlib 支持的其他关键字hist
。例如,可以通过orientation='horizontal'
和cumulative=True
绘制水平和累积直方图。
In [30]: plt.figure();
In [31]: df4["a"].plot.hist(orientation="horizontal", cumulative=True);
查看hist
方法和matplotlib hist 文档以获取更多信息。
仍然可以使用现有接口DataFrame.hist
绘制直方图。
In [32]: plt.figure();
In [33]: df["A"].diff().hist();
DataFrame.hist()
在多个子图上绘制列的直方图:
In [34]: plt.figure();
In [35]: df.diff().hist(color="k", alpha=0.5, bins=50);
by
关键字可用于绘制分组直方图:
In [36]: data = pd.Series(np.random.randn(1000))
In [37]: data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4));
此外,by
关键字也可以在DataFrame.plot.hist()
中指定。
自 1.4.0 版更改。
In [38]: data = pd.DataFrame(
....: {
....: "a": np.random.choice(["x", "y", "z"], 1000),
....: "b": np.random.choice(["e", "f", "g"], 1000),
....: "c": np.random.randn(1000),
....: "d": np.random.randn(1000) - 1,
....: },
....: )
....:
In [39]: data.plot.hist(by=["a", "b"], figsize=(10, 5));
### 箱线图
调用Series.plot.box()
和DataFrame.plot.box()
,或DataFrame.boxplot()
来绘制箱线图以可视化每列中的值的分布。
例如,这是一个表示在 [0,1) 上的均匀随机变量的 10 次观测的五次试验的箱线图。
In [40]: df = pd.DataFrame(np.random.rand(10, 5), columns=["A", "B", "C", "D", "E"])
In [41]: df.plot.box();
通过传递 color
关键字可以给箱线图着色。您可以传递一个 dict
,其键为 boxes
、whiskers
、medians
和 caps
。如果字典中缺少某些键,则对应艺术品将使用默认颜色。此外,箱线图还有 sym
关键字来指定离群值的样式。
当您通过 color
关键字传递其他类型的参数时,它将直接传递给所有 boxes
、whiskers
、medians
和 caps
的着色。
颜色应用于要绘制的每个箱子。如果您需要更复杂的着色,可以通过传递 return_type 获取每个绘制的艺术品。
In [42]: color = {
....: "boxes": "DarkGreen",
....: "whiskers": "DarkOrange",
....: "medians": "DarkBlue",
....: "caps": "Gray",
....: }
....:
In [43]: df.plot.box(color=color, sym="r+");
此外,您还可以传递 matplotlib boxplot
支持的其他关键字。例如,通过 vert=False
和 positions
关键字可以绘制水平和自定义位置的箱线图。
In [44]: df.plot.box(vert=False, positions=[1, 4, 5, 6, 8]);
请查看boxplot
方法和matplotlib 箱线图文档 以获取更多信息。
仍然可以使用现有接口 DataFrame.boxplot
绘制箱线图。
In [45]: df = pd.DataFrame(np.random.rand(10, 5))
In [46]: plt.figure();
In [47]: bp = df.boxplot()
您可以使用 by
关键字参数创建分层箱线图以创建分组。例如,
In [48]: df = pd.DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
In [49]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [50]: plt.figure();
In [51]: bp = df.boxplot(by="X")
你也可以传递一部分列来绘制图表,以及按多列进行分组:
In [52]: df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
In [53]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [54]: df["Y"] = pd.Series(["A", "B", "A", "B", "A", "B", "A", "B", "A", "B"])
In [55]: plt.figure();
In [56]: bp = df.boxplot(column=["Col1", "Col2"], by=["X", "Y"])
你还可以使用DataFrame.plot.box()
创建分组,例如:
从版本 1.4.0 开始更改。
In [57]: df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
In [58]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [59]: plt.figure();
In [60]: bp = df.plot.box(column=["Col1", "Col2"], by="X")
在boxplot
中,返回类型可以通过return_type
关键字控制。有效选择为{"axes", "dict", "both", None}
。由DataFrame.boxplot
创建的分面,使用by
关键字,也会影响输出类型:
return_type |
分面 | 输出类型 |
---|---|---|
None |
否 | 轴 |
None |
是 | 2-D 轴数组 |
'axes' |
否 | 轴 |
'axes' |
是 | 轴系列 |
'dict' |
否 | 艺术家字典 |
'dict' |
是 | 艺术家字典系列 |
'both' |
否 | 命名元组 |
'both' |
是 | 命名元组系列 |
Groupby.boxplot
始终返回return_type
的Series
。
In [61]: np.random.seed(1234)
In [62]: df_box = pd.DataFrame(np.random.randn(50, 2))
In [63]: df_box["g"] = np.random.choice(["A", "B"], size=50)
In [64]: df_box.loc[df_box["g"] == "B", 1] += 3
In [65]: bp = df_box.boxplot(by="g")
上面的子图首先按数值列分割,然后按g
列的值分割。下面的子图首先按g
的值分割,然后按数值列分割。
In [66]: bp = df_box.groupby("g").boxplot()
### 面积图
你可以使用Series.plot.area()
和DataFrame.plot.area()
创建面积图。面积图默认堆叠。要生成堆叠的面积图,每列必须是全部正值或全部负值。
当输入数据包含NaN
时,它将自动填充为 0。如果要删除或用不同值填充,请在调用plot
之前使用dataframe.dropna()
或dataframe.fillna()
。
In [67]: df = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
In [68]: df.plot.area();
要生成未堆叠的图,请传递stacked=False
。除非另有说明,否则 alpha 值设置为 0.5:
In [69]: df.plot.area(stacked=False);
### 散点图
散点图可以通过使用DataFrame.plot.scatter()
方法绘制。散点图需要 x 轴和 y 轴的数值列。这些可以通过x
和y
关键字指定。
In [70]: df = pd.DataFrame(np.random.rand(50, 4), columns=["a", "b", "c", "d"])
In [71]: df["species"] = pd.Categorical(
....: ["setosa"] * 20 + ["versicolor"] * 20 + ["virginica"] * 10
....: )
....:
In [72]: df.plot.scatter(x="a", y="b");
要在单个轴上绘制多个列组,请重复plot
方法并指定目标ax
。建议指定color
和label
关键字以区分每个组。
In [73]: ax = df.plot.scatter(x="a", y="b", color="DarkBlue", label="Group 1")
In [74]: df.plot.scatter(x="c", y="d", color="DarkGreen", label="Group 2", ax=ax);
关键字 c
可以作为列的名称,为每个点提供颜色:
In [75]: df.plot.scatter(x="a", y="b", c="c", s=50);
如果传递给 c
的是一个分类列,则会生成一个离散的颜色条:
新版本 1.3.0 中添加。
In [76]: df.plot.scatter(x="a", y="b", c="species", cmap="viridis", s=50);
你可以传递 matplotlib
支持的其他关键字给 scatter
。下面的示例展示了使用 DataFrame
列作为气泡大小的气泡图。
In [77]: df.plot.scatter(x="a", y="b", s=df["c"] * 200);
查看 scatter
方法和 matplotlib scatter 文档 了解更多。### 六边形 bin 图
你可以使用 DataFrame.plot.hexbin()
创建六边形 bin 图。如果你的数据过于密集而无法单独绘制每个点,则六边形 bin 图可以作为散点图的有用替代品。
In [78]: df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
In [79]: df["b"] = df["b"] + np.arange(1000)
In [80]: df.plot.hexbin(x="a", y="b", gridsize=25);
一个有用的关键字参数是 gridsize
;它控制 x 方向上的六边形数量,默认为 100。更大的 gridsize
意味着更多、更小的 bins。
默认情况下,计算每个 (x, y)
点周围的计数直方图。你可以通过将值传递给 C
和 reduce_C_function
参数来指定替代聚合。C
指定每个 (x, y)
点的值,而 reduce_C_function
是一个函数,接受一个参数,将一个 bin 中的所有值减少到一个单一的数字(例如 mean
、max
、sum
、std
)。在这个示例中,位置由列 a
和 b
给出,而值由列 z
给出。使用 NumPy 的 max
函数对 bins 进行聚合。
In [81]: df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
In [82]: df["b"] = df["b"] + np.arange(1000)
In [83]: df["z"] = np.random.uniform(0, 3, 1000)
In [84]: df.plot.hexbin(x="a", y="b", C="z", reduce_C_function=np.max, gridsize=25);
查看 hexbin
方法和 matplotlib hexbin 文档 了解更多。### 饼图
您可以使用DataFrame.plot.pie()
或Series.plot.pie()
创建饼图。如果您的数据包含任何NaN
,它们将自动填充为 0。如果数据中有任何负值,将引发ValueError
。
In [85]: series = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"], name="series")
In [86]: series.plot.pie(figsize=(6, 6));
对于饼图,最好使用正方形图形,即图形纵横比为 1。您可以创建宽度和高度相等的图形,或者在绘图后通过调用ax.set_aspect('equal')
来强制纵横比相等。
请注意,使用DataFrame
创建饼图需要通过y
参数指定目标列或subplots=True
。当指定y
时,将绘制所选列的饼图。如果指定了subplots=True
,将为每列绘制饼图子图。默认情况下,每个饼图中都会绘制图例;指定legend=False
以隐藏图例。
In [87]: df = pd.DataFrame(
....: 3 * np.random.rand(4, 2), index=["a", "b", "c", "d"], columns=["x", "y"]
....: )
....:
In [88]: df.plot.pie(subplots=True, figsize=(8, 4));
您可以使用labels
和colors
关键字来指定每个楔形的标签和颜色。
警告
大多数 pandas 绘图使用label
和color
参数(请注意这两个参数上没有“s”)。为了与matplotlib.pyplot.pie()
保持一致,您必须使用labels
和colors
。
如果要隐藏楔形标签,请指定labels=None
。如果指定了fontsize
,则该值将应用于楔形标签。此外,matplotlib.pyplot.pie()
支持的其他关键字也可以使用。
In [89]: series.plot.pie(
....: labels=["AA", "BB", "CC", "DD"],
....: colors=["r", "g", "b", "c"],
....: autopct="%.2f",
....: fontsize=20,
....: figsize=(6, 6),
....: );
....:
如果传递的值总和小于 1.0,则它们将被重新缩放,使其总和为 1。
In [90]: series = pd.Series([0.1] * 4, index=["a", "b", "c", "d"], name="series2")
In [91]: series.plot.pie(figsize=(6, 6));
查看更多内容,请参阅matplotlib 饼图文档。 ## 使用缺失数据绘图
pandas 在绘制包含缺失数据的DataFrame
或Series
时会尝试实用。根据绘图类型,缺失值将被删除、省略或填充。
绘图类型 | NaN 处理 |
---|---|
折线图 | 在 NaN 处留空 |
折线图(堆叠) | 填充 0 |
条形图 | 填充 0 |
散点图 | 删除 NaN |
直方图 | 删除 NaN(列) |
箱线图 | 删除 NaN(列) |
面积图 | 填充 0 |
KDE | 删除 NaN(列) |
六边形图 | 删除 NaN |
饼图 | 填充 0 |
如果默认设置不符合您的要求,或者您想明确指定如何处理缺失值,请考虑在绘图之前使用fillna()
或dropna()
。## 绘图工具
这些函数可以从pandas.plotting
中导入,并将Series
或DataFrame
作为参数。
散点矩阵图
你可以使用pandas.plotting
中的scatter_matrix
方法创建散点图矩阵:
In [92]: from pandas.plotting import scatter_matrix
In [93]: df = pd.DataFrame(np.random.randn(1000, 4), columns=["a", "b", "c", "d"])
In [94]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal="kde");
### 密度图
你可以使用Series.plot.kde()
和DataFrame.plot.kde()
方法创建密度图。
In [95]: ser = pd.Series(np.random.randn(1000))
In [96]: ser.plot.kde();
### 安德鲁斯曲线
安德鲁斯曲线允许我们将多变量数据绘制为大量曲线,这些曲线是使用样本属性作为傅立叶级数的系数创建的,详见维基百科条目。通过为每个类别的曲线着不同颜色,可以可视化数据聚类。属于同一类别样本的曲线通常会更接近并形成更大的结构。
注意:可在此处获取“Iris”数据集。
In [97]: from pandas.plotting import andrews_curves
In [98]: data = pd.read_csv("data/iris.data")
In [99]: plt.figure();
In [100]: andrews_curves(data, "Name");
### 平行坐标
平行坐标是一种用于绘制多变量数据的绘图技术,详见维基百科条目。平行坐标允许我们看到数据中的聚类,并通过视觉估计其他统计数据。使用平行坐标,点被表示为连接的线段。每条垂直线代表一个属性。一组连接的线段代表一个数据点。倾向于聚类的点会更接近。
In [101]: from pandas.plotting import parallel_coordinates
In [102]: data = pd.read_csv("data/iris.data")
In [103]: plt.figure();
In [104]: parallel_coordinates(data, "Name");
### 滞后图
滞后图用于检查数据集或时间序列是否是随机的。随机数据不应在滞后图中显示任何结构。非随机结构意味着底层数据不是随机的。可以传递lag
参数,当lag=1
时,图形基本上是data[:-1]
vs. data[1:]
。
In [105]: from pandas.plotting import lag_plot
In [106]: plt.figure();
In [107]: spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)
In [108]: data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))
In [109]: lag_plot(data);
### 自相关图
自相关图通常用于检查时间序列中的随机性。这是通过计算不同时间滞后处的数据值的自相关来实现的。如果时间序列是随机的,这些自相关应该在任何时间滞后分离处接近零。如果时间序列是非随机的,那么一个或多个自相关将显着非零。图中显示的水平线对应于 95%和 99%的置信区间。虚线是 99%的置信区间。有关自相关图的更多信息,请参阅Wikipedia 条目。
In [110]: from pandas.plotting import autocorrelation_plot
In [111]: plt.figure();
In [112]: spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
In [113]: data = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
In [114]: autocorrelation_plot(data);
### Bootstrap 图
Bootstrap 图用于直观评估统计量(如均值、中位数、中程等)的不确定性。从数据集中选择指定大小的随机子集,计算该子集的统计量,然后重复该过程指定次数。生成的图和直方图构成了 Bootstrap 图。
In [115]: from pandas.plotting import bootstrap_plot
In [116]: data = pd.Series(np.random.rand(1000))
In [117]: bootstrap_plot(data, size=50, samples=500, color="grey");
### RadViz
RadViz 是一种可视化多变量数据的方法。它基于简单的弹簧张力最小化算法。基本上,您在平面上设置一堆点。在我们的情况下,它们在单位圆上等距分布。每个点代表一个单独的属性。然后,您假装数据集中的每个样本都通过弹簧连接到这些点,弹簧的刚度与该属性的数值成比例(它们被归一化为单位间隔)。我们的样本定居到的平面上的点(在我们的样本上作用的力处于平衡状态的地方)是我们的样本将被绘制的点。根据该样本属于哪个类别,它将以不同的颜色着色。有关更多信息,请参阅 R 包Radviz。
注意: “鸢尾花”数据集可在此处获取。
In [118]: from pandas.plotting import radviz
In [119]: data = pd.read_csv("data/iris.data")
In [120]: plt.figure();
In [121]: radviz(data, "Name");
## 绘图格式
设置绘图样式
从 1.5 版本开始,matplotlib 提供了一系列预配置的绘图样式。设置样式可用于轻松地给出所需的绘图外观。在创建绘图之前调用matplotlib.style.use(my_plot_style)
即可设置样式。例如,您可以写matplotlib.style.use('ggplot')
以获得 ggplot 风格的绘图。
您可以在matplotlib.style.available
中看到各种可用的样式名称,并且很容易尝试它们。
一般绘图样式参数
大多数绘图方法都有一组关键字参数,用于控制返回绘图的布局和格式:
In [122]: plt.figure();
In [123]: ts.plot(style="k--", label="Series");
对于每种类型的图(例如 line
、bar
、scatter
),将任何附加的参数关键字传递给相应的 matplotlib 函数(ax.plot()
、ax.bar()
、ax.scatter()
)。 这些可以用来控制额外的样式,超出了 pandas 提供的范围。
控制图例
您可以将 legend
参数设置为 False
以隐藏默认显示的图例。
In [124]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [125]: df = df.cumsum()
In [126]: df.plot(legend=False);
控制标签
您可以设置 xlabel
和 ylabel
参数以为绘图设置自定义标签,用于 x 和 y 轴。 默认情况下,pandas 将采用索引名称作为 xlabel,同时将其留空作为 ylabel。
In [127]: df.plot();
In [128]: df.plot(xlabel="new x", ylabel="new y");
比例
你可以传递logy
以获得对数刻度 Y 轴。
In [129]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [130]: ts = np.exp(ts.cumsum())
In [131]: ts.plot(logy=True);
还请参阅 logx
和 loglog
关键字参数。
在次要 y 轴上绘图
要在次要 y 轴上绘制数据,请使用 secondary_y
关键字:
In [132]: df["A"].plot();
In [133]: df["B"].plot(secondary_y=True, style="g");
要在 DataFrame
中绘制某些列,请将列名传递给 secondary_y
关键字:
In [134]: plt.figure();
In [135]: ax = df.plot(secondary_y=["A", "B"])
In [136]: ax.set_ylabel("CD scale");
In [137]: ax.right_ax.set_ylabel("AB scale");
请注意,在图例中,自动标记在次要 y 轴上绘制的列为“(right)” 。 要关闭自动标记,请使用 mark_right=False
关键字:
In [138]: plt.figure();
In [139]: df.plot(secondary_y=["A", "B"], mark_right=False);
### 时间序列图的自定义格式化程序
pandas 为时间序列图提供了自定义格式化程序。 这些更改日期和时间的轴标签的格式。 默认情况下,自定义格式化程序仅应用于由 pandas 使用 DataFrame.plot()
或 Series.plot()
创建的图。 要使它们应用于所有图,包括由 matplotlib 制作的图,请设置选项 pd.options.plotting.matplotlib.register_converters = True
或使用 pandas.plotting.register_matplotlib_converters()
。
抑制刻度分辨率调整
pandas 包括用于常规频率时间序列数据的自动刻度分辨率调整。对于 pandas 无法推断频率信息的有限情况(例如,在外部创建的twinx
中),您可以选择抑制此行为以进行对齐。
这是默认行为,请注意 x 轴刻度标签的执行方式:
In [140]: plt.figure();
In [141]: df["A"].plot();
使用x_compat
参数,您可以抑制此行为:
In [142]: plt.figure();
In [143]: df["A"].plot(x_compat=True);
如果有多个需要抑制的图,可以在with
语句中使用pandas.plotting.plot_params
中的use
方法:
In [144]: plt.figure();
In [145]: with pd.plotting.plot_params.use("x_compat", True):
.....: df["A"].plot(color="r")
.....: df["B"].plot(color="g")
.....: df["C"].plot(color="b")
.....:
自动日期刻度调整
TimedeltaIndex
现在使用本机 matplotlib 刻度定位器方法,对于刻度标签重叠的图形,调用 matplotlib 的自动日期刻度调整非常有用。
有关更多信息,请参阅autofmt_xdate
方法和matplotlib 文档。
子图
DataFrame
中的每个Series
可以使用subplots
关键字在不同的轴上绘制:
In [146]: df.plot(subplots=True, figsize=(6, 6));
使用布局并针对多个轴
子图的布局可以通过layout
关键字指定。它可以接受(行数,列数)
。layout
关键字也可以在hist
和boxplot
中使用。如果输入无效,将引发ValueError
。
由layout
指定的行 x 列包含的轴数必须大于所需子图的数量。如果layout
可以容纳更多轴,那么空白轴将不会被绘制。类似于 NumPy 数组的reshape
方法,您可以在一个维度上使用-1
来自动计算所需的行数或列数,给定另一个维度。
In [147]: df.plot(subplots=True, layout=(2, 3), figsize=(6, 6), sharex=False);
上面的示例与使用以下内容相同:
In [148]: df.plot(subplots=True, layout=(2, -1), figsize=(6, 6), sharex=False);
所需的列数(3)是从要绘制的系列数和给定的行数(2)推断出来的。
您可以通过ax
关键字以类似列表的方式传递预先创建的多个轴。这允许更复杂的布局。传递的轴必须与正在绘制的子图数量相同。
当通过ax
关键字传递多个轴时,layout
、sharex
和sharey
关键字不会影响输出。您应该明确传递sharex=False
和sharey=False
,否则将会看到警告。
In [149]: fig, axes = plt.subplots(4, 4, figsize=(9, 9))
In [150]: plt.subplots_adjust(wspace=0.5, hspace=0.5)
In [151]: target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]]
In [152]: target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]]
In [153]: df.plot(subplots=True, ax=target1, legend=False, sharex=False, sharey=False);
In [154]: (-df).plot(subplots=True, ax=target2, legend=False, sharex=False, sharey=False);
另一个选项是通过在Series.plot()
中传递一个ax
参数来在特定轴上绘制:
In [155]: np.random.seed(123456)
In [156]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [157]: ts = ts.cumsum()
In [158]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [159]: df = df.cumsum()
In [160]: fig, axes = plt.subplots(nrows=2, ncols=2)
In [161]: plt.subplots_adjust(wspace=0.2, hspace=0.5)
In [162]: df["A"].plot(ax=axes[0, 0]);
In [163]: axes[0, 0].set_title("A");
In [164]: df["B"].plot(ax=axes[0, 1]);
In [165]: axes[0, 1].set_title("B");
In [166]: df["C"].plot(ax=axes[1, 0]);
In [167]: axes[1, 0].set_title("C");
In [168]: df["D"].plot(ax=axes[1, 1]);
In [169]: axes[1, 1].set_title("D");
### 带有误差条的绘图
在DataFrame.plot()
和 Series.plot()
中支持使用误差条绘图。
水平和垂直误差条可以分别通过 xerr
和 yerr
关键字参数传递给 plot()
。误差值可以使用多种格式指定:
-
作为与绘图的
DataFrame
的列名匹配的误差的DataFrame
或字典,或与Series
的name
属性匹配的误差。 -
作为一个字符串,指示绘图的
DataFrame
中哪些列包含误差值。 -
作为原始值(
list
、tuple
或np.ndarray
)。必须与绘图的DataFrame
/Series
的长度相同。
下面是从原始数据轻松绘制组均值和标准差的一个示例。
# Generate the data
In [170]: ix3 = pd.MultiIndex.from_arrays(
.....: [
.....: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
.....: ["foo", "foo", "foo", "bar", "bar", "foo", "foo", "bar", "bar", "bar"],
.....: ],
.....: names=["letter", "word"],
.....: )
.....:
In [171]: df3 = pd.DataFrame(
.....: {
.....: "data1": [9, 3, 2, 4, 3, 2, 4, 6, 3, 2],
.....: "data2": [9, 6, 5, 7, 5, 4, 5, 6, 5, 1],
.....: },
.....: index=ix3,
.....: )
.....:
# Group by index labels and take the means and standard deviations
# for each group
In [172]: gp3 = df3.groupby(level=("letter", "word"))
In [173]: means = gp3.mean()
In [174]: errors = gp3.std()
In [175]: means
Out[175]:
data1 data2
letter word
a bar 3.500000 6.000000
foo 4.666667 6.666667
b bar 3.666667 4.000000
foo 3.000000 4.500000
In [176]: errors
Out[176]:
data1 data2
letter word
a bar 0.707107 1.414214
foo 3.785939 2.081666
b bar 2.081666 2.645751
foo 1.414214 0.707107
# Plot
In [177]: fig, ax = plt.subplots()
In [178]: means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
在这种情况下,也支持不对称误差条,但必须提供原始误差值。对于长度为N
的 Series
,应提供一个 2xN
的数组,表示下限和上限(或左右)误差。对于 MxN
的DataFrame
,不对称误差应该是一个 Mx2xN
的数组。
下面是使用不对称误差条绘制最小/最大范围的一个示例。
In [179]: mins = gp3.min()
In [180]: maxs = gp3.max()
# errors should be positive, and defined in the order of lower, upper
In [181]: errors = [[means[c] - mins[c], maxs[c] - means[c]] for c in df3.columns]
# Plot
In [182]: fig, ax = plt.subplots()
In [183]: means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
### 绘制表格
使用 matplotlib 表格绘图现在支持在DataFrame.plot()
和 Series.plot()
中使用 table
关键字。table
关键字可以接受 bool
、DataFrame
或 Series
。绘制表格的简单方法是指定 table=True
。数据将被转置以符合 matplotlib 的默认布局。
In [184]: np.random.seed(123456)
In [185]: fig, ax = plt.subplots(1, 1, figsize=(7, 6.5))
In [186]: df = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
In [187]: ax.xaxis.tick_top() # Display x-axis ticks on top.
In [188]: df.plot(table=True, ax=ax);
此外,您可以传递不同的 DataFrame
或 Series
给 table
关键字。数据将按照 print 方法中显示的方式绘制(不会自动转置)。如果需要,应手动转置,如下面的示例所示。
In [189]: fig, ax = plt.subplots(1, 1, figsize=(7, 6.75))
In [190]: ax.xaxis.tick_top() # Display x-axis ticks on top.
In [191]: df.plot(table=np.round(df.T, 2), ax=ax);
还存在一个辅助函数 pandas.plotting.table
,它从 DataFrame
或 Series
创建一个表,并将其添加到 matplotlib.Axes
实例中。此函数可以接受 matplotlib table 具有的关键字。
In [192]: from pandas.plotting import table
In [193]: fig, ax = plt.subplots(1, 1)
In [194]: table(ax, np.round(df.describe(), 2), loc="upper right", colWidths=[0.2, 0.2, 0.2]);
In [195]: df.plot(ax=ax, ylim=(0, 2), legend=None);
注意:您可以使用 axes.tables
属性在轴上获取表实例,以进行进一步的装饰。有关更多信息,请参阅 matplotlib 表格文档。 ### 色图
绘制大量列时可能出现的一个潜在问题是,由于默认颜色中的重复,一些系列很难区分。为了解决这个问题,DataFrame
绘图支持使用 colormap
参数,该参数接受 Matplotlib colormap 或一个字符串,该字符串是注册到 Matplotlib 的 colormap 的名称。默认 matplotlib 色图的可视化参考 此处。
由于 matplotlib 不直接支持基于线的图的色图,所以颜色是根据 DataFrame
中的列数确定的均匀间距选择的。没有考虑背景颜色,因此一些色图会产生不易看到的线。
要使用 cubehelix 色图,我们可以传递 colormap='cubehelix'
。
In [196]: np.random.seed(123456)
In [197]: df = pd.DataFrame(np.random.randn(1000, 10), index=ts.index)
In [198]: df = df.cumsum()
In [199]: plt.figure();
In [200]: df.plot(colormap="cubehelix");
或者,我们可以传递色图本身:
In [201]: from matplotlib import cm
In [202]: plt.figure();
In [203]: df.plot(colormap=cm.cubehelix);
色图也可以用于其他绘图类型,如条形图:
In [204]: np.random.seed(123456)
In [205]: dd = pd.DataFrame(np.random.randn(10, 10)).map(abs)
In [206]: dd = dd.cumsum()
In [207]: plt.figure();
In [208]: dd.plot.bar(colormap="Greens");
平行坐标图:
In [209]: plt.figure();
In [210]: parallel_coordinates(data, "Name", colormap="gist_rainbow");
Andrews 曲线图:
In [211]: plt.figure();
In [212]: andrews_curves(data, "Name", colormap="winter");
直接使用 Matplotlib 绘图
在某些情况下,直接使用 matplotlib 准备图形可能仍然更可取或必要,例如当 pandas 尚不支持某种类型的图形或自定义时。Series
和DataFrame
对象的行为类似于数组,因此可以直接将它们传递给 matplotlib 函数,而无需显式转换。
pandas 还自动注册了识别日期索引的格式化程序和定位器,从而将日期和时间支持扩展到几乎所有 matplotlib 中可用的绘图类型。尽管这种格式化不提供通过 pandas 绘图时获得的相同精细度水平,但在绘制大量点时可能更快。
In [213]: np.random.seed(123456)
In [214]: price = pd.Series(
.....: np.random.randn(150).cumsum(),
.....: index=pd.date_range("2000-1-1", periods=150, freq="B"),
.....: )
.....:
In [215]: ma = price.rolling(20).mean()
In [216]: mstd = price.rolling(20).std()
In [217]: plt.figure();
In [218]: plt.plot(price.index, price, "k");
In [219]: plt.plot(ma.index, ma, "b");
In [220]: plt.fill_between(mstd.index, ma - 2 * mstd, ma + 2 * mstd, color="b", alpha=0.2);
绘图后端
pandas 可以通过第三方绘图后端进行扩展。主要思想是让用户选择一个基于 Matplotlib 提供的绘图后端不同的绘图后端。
这可以通过在plot
函数中将‘backend.module’作为参数backend
传递来实现。例如:
>>> Series([1, 2, 3]).plot(backend="backend.module")
或者,您也���以全局设置此选项,这样您就不需要在每个plot
调用中指定关键字。例如:
>>> pd.set_option("plotting.backend", "backend.module")
>>> pd.Series([1, 2, 3]).plot()
或者:
>>> pd.options.plotting.backend = "backend.module"
>>> pd.Series([1, 2, 3]).plot()
这基本上等同于:
>>> import backend.module
>>> backend.module.plot(pd.Series([1, 2, 3]))
然后,后端模块可以使用其他可视化工具(Bokeh、Altair、hvplot 等)生成图形。一些为 pandas 实现后端的库列在生态系统页面上。
开发人员指南可以在pandas.pydata.org/docs/dev/development/extending.html#plotting-backends
找到
基本绘图:plot
我们将演示基础知识,有关一些高级策略,请参见食谱。
Series 和 DataFrame 上的plot
方法只是对plt.plot()
的简单包装:
In [3]: np.random.seed(123456)
In [4]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [5]: ts = ts.cumsum()
In [6]: ts.plot();
如果索引由日期组成,则调用gcf().autofmt_xdate()
尝试根据上述格式化 x 轴。
在 DataFrame 上,plot()
是一个方便的方法,用于绘制所有带有标签的列:
In [7]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [8]: df = df.cumsum()
In [9]: plt.figure();
In [10]: df.plot();
您可以使用plot()
中的x
和y
关键字绘制一列与另一列的图形:
In [11]: df3 = pd.DataFrame(np.random.randn(1000, 2), columns=["B", "C"]).cumsum()
In [12]: df3["A"] = pd.Series(list(range(len(df))))
In [13]: df3.plot(x="A", y="B");
注意
要了解更多格式和样式选项,请参见下面的格式化。
其他图形
绘图方法除了默认的线图之外,还允许使用一些其他样式的绘图。这些方法可以作为 plot()
的 kind
关键字参数提供,包括:
-
‘bar’ 或 ‘barh’ 用于条形图
-
‘hist’ 用于直方图
-
‘box’ 用于箱线图
-
‘kde’ 或 ‘density’ 用于密度图
-
‘area’ 用于面积图
-
‘scatter’ 用于散点图
-
‘hexbin’ 用于六边形二进制图
-
‘pie’ 用于饼图
例如,可以通过以下方式创建条形图:
In [14]: plt.figure();
In [15]: df.iloc[5].plot(kind="bar");
您还可以使用方法 DataFrame.plot.<kind>
来创建这些其他图,而不是提供 kind
关键字参数。这样可以更容易地发现绘图方法和它们使用的具体参数:
In [16]: df = pd.DataFrame()
In [17]: df.plot.<TAB> # noqa: E225, E999
df.plot.area df.plot.barh df.plot.density df.plot.hist df.plot.line df.plot.scatter
df.plot.bar df.plot.box df.plot.hexbin df.plot.kde df.plot.pie
除了这些 kind
,还有 DataFrame.hist() 和 DataFrame.boxplot() 方法,它们使用单独的界面。
最后,pandas.plotting
中有几个 绘图函数,它们将 Series
或 DataFrame
作为参数。这些包括:
-
散点矩阵
-
安德鲁曲线
-
平行坐标
-
滞后图
-
自相关图
-
自举图
-
RadViz
图表也可以装饰有 误差条 或 表格。
条形图
对于带标签的非时间序列数据,您可能希望生成条形图:
In [18]: plt.figure();
In [19]: df.iloc[5].plot.bar();
In [20]: plt.axhline(0, color="k");
调用 DataFrame 的 plot.bar()
方法会生成多条条形图:
In [21]: df2 = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
In [22]: df2.plot.bar();
要生成堆叠条形图,请传递 stacked=True
:
In [23]: df2.plot.bar(stacked=True);
要获得水平条形图,请使用 barh
方法:
In [24]: df2.plot.barh(stacked=True);
### 直方图
直方图可以通过使用DataFrame.plot.hist()
和 Series.plot.hist()
方法绘制。
In [25]: df4 = pd.DataFrame(
....: {
....: "a": np.random.randn(1000) + 1,
....: "b": np.random.randn(1000),
....: "c": np.random.randn(1000) - 1,
....: },
....: columns=["a", "b", "c"],
....: )
....:
In [26]: plt.figure();
In [27]: df4.plot.hist(alpha=0.5);
可以使用stacked=True
堆叠直方图。可以使用bins
关键字更改箱子大小。
In [28]: plt.figure();
In [29]: df4.plot.hist(stacked=True, bins=20);
您可以传递 matplotlib 支持的其他关键字。例如,可以通过orientation='horizontal'
和cumulative=True
绘制水平和累积直方图。
In [30]: plt.figure();
In [31]: df4["a"].plot.hist(orientation="horizontal", cumulative=True);
查看 hist
方法和 matplotlib 直方图文档 以获取更多信息。
现有的接口DataFrame.hist
用于绘制直方图仍然可以使用。
In [32]: plt.figure();
In [33]: df["A"].diff().hist();
DataFrame.hist()
在多个子图上绘制列的直方图:
In [34]: plt.figure();
In [35]: df.diff().hist(color="k", alpha=0.5, bins=50);
可以指定by
关键字以绘制分组直方图:
In [36]: data = pd.Series(np.random.randn(1000))
In [37]: data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4));
另外,在 DataFrame.plot.hist()
中也可以指定by
关键字。
从版本 1.4.0 开始更改。
In [38]: data = pd.DataFrame(
....: {
....: "a": np.random.choice(["x", "y", "z"], 1000),
....: "b": np.random.choice(["e", "f", "g"], 1000),
....: "c": np.random.randn(1000),
....: "d": np.random.randn(1000) - 1,
....: },
....: )
....:
In [39]: data.plot.hist(by=["a", "b"], figsize=(10, 5));
### 箱线图
绘制箱线图可以调用Series.plot.box()
和 DataFrame.plot.box()
,或者 DataFrame.boxplot()
来可视化每一列中值的分布。
例如,这里是表示五次对 [0,1) 上的均匀随机变量进行的 10 次观察的箱线图。
In [40]: df = pd.DataFrame(np.random.rand(10, 5), columns=["A", "B", "C", "D", "E"])
In [41]: df.plot.box();
通过传递color
关键字可以给箱线图上色。您可以传递一个dict
,其键为boxes
、whiskers
、medians
和caps
。如果字典中缺少某些键,则对应艺术家使用默认颜色。此外,箱线图具有sym
关键字,用于指定异常值的样式。
当您通过color
关键字传递其他类型的参数时,它将直接传递给 matplotlib 所有boxes
、whiskers
、medians
和caps
的着色。
颜色应用于要绘制的每个箱子。如果您需要更复杂的着色,可以通过传递 return_type 来获取每个绘制的艺术家。
In [42]: color = {
....: "boxes": "DarkGreen",
....: "whiskers": "DarkOrange",
....: "medians": "DarkBlue",
....: "caps": "Gray",
....: }
....:
In [43]: df.plot.box(color=color, sym="r+");
此外,您还可以传递 matplotlib boxplot
支持的其他关键字。例如,通过vert=False
和positions
关键字可以绘制水平和自定义位置的箱线图。
In [44]: df.plot.box(vert=False, positions=[1, 4, 5, 6, 8]);
更多信息请参见boxplot
方法和matplotlib 箱线图文档。
仍然可以使用现有接口DataFrame.boxplot
来绘制箱线图。
In [45]: df = pd.DataFrame(np.random.rand(10, 5))
In [46]: plt.figure();
In [47]: bp = df.boxplot()
你可以使用by
关键字参数创建分组来创建分层箱线图。例如,
In [48]: df = pd.DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
In [49]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [50]: plt.figure();
In [51]: bp = df.boxplot(by="X")
您还可以传递要绘制的列的子集,以及按多个列分组:
In [52]: df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
In [53]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [54]: df["Y"] = pd.Series(["A", "B", "A", "B", "A", "B", "A", "B", "A", "B"])
In [55]: plt.figure();
In [56]: bp = df.boxplot(column=["Col1", "Col2"], by=["X", "Y"])
你也可以使用DataFrame.plot.box()
创建分组,例如:
从版本 1.4.0 开始更改。
In [57]: df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
In [58]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [59]: plt.figure();
In [60]: bp = df.plot.box(column=["Col1", "Col2"], by="X")
在boxplot
中,返回类型可以通过return_type
关键字控制。有效选择为{"axes", "dict", "both", None}
。由带有by
关键字的DataFrame.boxplot
创建的分面图也会影响输出类型:
return_type |
分面 | 输出类型 |
---|---|---|
None |
否 | axes |
None |
是 | 2-D ndarray of axes |
'axes' |
否 | axes |
'axes' |
是 | axes 的 Series |
'dict' |
否 | 艺术家的字典 |
'dict' |
是 | 艺术家字典的 Series |
'both' |
否 | 命名元组 |
'both' |
是 | 命名元组的 Series |
Groupby.boxplot
总是返回一个return_type
的Series
。
In [61]: np.random.seed(1234)
In [62]: df_box = pd.DataFrame(np.random.randn(50, 2))
In [63]: df_box["g"] = np.random.choice(["A", "B"], size=50)
In [64]: df_box.loc[df_box["g"] == "B", 1] += 3
In [65]: bp = df_box.boxplot(by="g")
上面的子图首先按数字列分割,然后按g
列的值分割。下面的子图首先按g
的值分割,然后按数字列分割。
In [66]: bp = df_box.groupby("g").boxplot()
### 区域图
您可以使用Series.plot.area()
和DataFrame.plot.area()
创建区域图。默认情况下,区域图是堆叠的。要产生堆叠的区域图,每列必须是所有正值或所有负值。
当输入数据包含NaN
时,它将自动填充为 0。如果要删除或用不同值填充,请在调用plot
之前使用dataframe.dropna()
或dataframe.fillna()
。
In [67]: df = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
In [68]: df.plot.area();
要生成一个未堆叠的图,请传递stacked=False
。除非另有说明,否则 alpha 值设置为 0.5:
In [69]: df.plot.area(stacked=False);
### 散点图
可以使用DataFrame.plot.scatter()
方法绘制散点图。散点图需要 x 轴和 y 轴的数值列。这些可以通过x
和y
关键字指定。
In [70]: df = pd.DataFrame(np.random.rand(50, 4), columns=["a", "b", "c", "d"])
In [71]: df["species"] = pd.Categorical(
....: ["setosa"] * 20 + ["versicolor"] * 20 + ["virginica"] * 10
....: )
....:
In [72]: df.plot.scatter(x="a", y="b");
要在单个轴上绘制多个列组,请重复plot
方法并指定目标ax
。建议指定color
和label
关键字以区分每个组。
In [73]: ax = df.plot.scatter(x="a", y="b", color="DarkBlue", label="Group 1")
In [74]: df.plot.scatter(x="c", y="d", color="DarkGreen", label="Group 2", ax=ax);
关键字c
可以作为列名给出,为每个点提供颜色:
In [75]: df.plot.scatter(x="a", y="b", c="c", s=50);
如果将分类列传递给c
,则将生成离散的颜色条:
新版本 1.3.0 中。
In [76]: df.plot.scatter(x="a", y="b", c="species", cmap="viridis", s=50);
你可以传递其他由 matplotlib 支持的关键字scatter
。下面的示例显示了使用DataFrame
列作为气泡大小的气泡图。
In [77]: df.plot.scatter(x="a", y="b", s=df["c"] * 200);
有关更多信息,请参阅scatter
方法和matplotlib scatter 文档。### 六边形箱图
您可以使用DataFrame.plot.hexbin()
创建六边形箱图。如果您的数据过于密集而无法单独绘制每个点,则六边形箱图可以是散点图的有用替代品。
In [78]: df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
In [79]: df["b"] = df["b"] + np.arange(1000)
In [80]: df.plot.hexbin(x="a", y="b", gridsize=25);
一个有用的关键字参数是gridsize
;它控制 x 方向上的六边形数量,默认为 100。较大的gridsize
意味着更多、更小的箱子。
默认情况下,计算每个(x, y)
点周围计数的直方图。你可以通过将值传递给C
和reduce_C_function
参数来指定替代聚合。C
指定每个(x, y)
点的值,reduce_C_function
是一个带有一个参数的函数,将一个 bin 中的所有值减少为一个单一数字(例如mean
、max
、sum
、std
)。在这个例子中,位置由列a
和b
给出,而值由列z
给出。使用 NumPy 的max
函数对 bin 进行聚合。
In [81]: df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
In [82]: df["b"] = df["b"] + np.arange(1000)
In [83]: df["z"] = np.random.uniform(0, 3, 1000)
In [84]: df.plot.hexbin(x="a", y="b", C="z", reduce_C_function=np.max, gridsize=25);
查看hexbin
方法和matplotlib hexbin 文档以了解更多信息。### 饼图
使用DataFrame.plot.pie()
或Series.plot.pie()
可以创建饼图。如果你的数据中包含任何NaN
,它们将自动填充为 0。如果数据中有任何负值,将会引发ValueError
。
In [85]: series = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"], name="series")
In [86]: series.plot.pie(figsize=(6, 6));
对于饼图,最好使用正方形图形,即图形纵横比为 1。你可以创建宽度和高度相等的图形,或者在绘图后通过调用ax.set_aspect('equal')
在返回的axes
对象上强制纵横比相等。
请注意,使用DataFrame
创建的饼图要求你通过y
参数或subplots=True
来指定目标列。当指定了y
时,将绘制所选列的饼图。如果指定了subplots=True
,将为每列绘制子图的饼图。默认情况下,每个饼图中都会绘制图例;指定legend=False
以隐藏它。
In [87]: df = pd.DataFrame(
....: 3 * np.random.rand(4, 2), index=["a", "b", "c", "d"], columns=["x", "y"]
....: )
....:
In [88]: df.plot.pie(subplots=True, figsize=(8, 4));
你可以使用labels
和colors
关键字指定每个楔形图的标签和颜色。
警告
大多数 pandas 绘图使用label
和color
参数(请注意这两个参数的缺少“s”)。为了与matplotlib.pyplot.pie()
保持一致,你必须使用labels
和colors
。
如果想要隐藏楔形图标签,请指定labels=None
。如果指定了fontsize
,该值将应用于楔形图标签。此外,还可以使用其他由matplotlib.pyplot.pie()
支持的关键字。
In [89]: series.plot.pie(
....: labels=["AA", "BB", "CC", "DD"],
....: colors=["r", "g", "b", "c"],
....: autopct="%.2f",
....: fontsize=20,
....: figsize=(6, 6),
....: );
....:
如果传递的值的总和小于 1.0,则它们将被重新缩放,使它们的总和为 1。
In [90]: series = pd.Series([0.1] * 4, index=["a", "b", "c", "d"], name="series2")
In [91]: series.plot.pie(figsize=(6, 6));
更多内容请参阅matplotlib 饼图文档。### 条形图
对于带有标签的非时间序列数据,您可能希望生成一个条形图:
In [18]: plt.figure();
In [19]: df.iloc[5].plot.bar();
In [20]: plt.axhline(0, color="k");
调用 DataFrame 的plot.bar()
方法会生成多个条形图:
In [21]: df2 = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
In [22]: df2.plot.bar();
要生成堆叠条形图,请传递stacked=True
:
In [23]: df2.plot.bar(stacked=True);
要获得水平条形图,请使用barh
方法:
In [24]: df2.plot.barh(stacked=True);
### 直方图
可以使用DataFrame.plot.hist()
和Series.plot.hist()
方法绘制直方图。
In [25]: df4 = pd.DataFrame(
....: {
....: "a": np.random.randn(1000) + 1,
....: "b": np.random.randn(1000),
....: "c": np.random.randn(1000) - 1,
....: },
....: columns=["a", "b", "c"],
....: )
....:
In [26]: plt.figure();
In [27]: df4.plot.hist(alpha=0.5);
可以使用stacked=True
堆叠直方图。可以使用bins
关键字更改 bin 大小。
In [28]: plt.figure();
In [29]: df4.plot.hist(stacked=True, bins=20);
您可以传递 matplotlib hist
支持的其他关键字。例如,可以通过orientation='horizontal'
和cumulative=True
绘制水平和累积直方图。
In [30]: plt.figure();
In [31]: df4["a"].plot.hist(orientation="horizontal", cumulative=True);
更多内容请参阅hist
方法和matplotlib hist 文档。
仍然可以使用现有的接口DataFrame.hist
来绘制直方图。
In [32]: plt.figure();
In [33]: df["A"].diff().hist();
DataFrame.hist()
在多个子图上绘制列的直方图:
In [34]: plt.figure();
In [35]: df.diff().hist(color="k", alpha=0.5, bins=50);
可以指定by
关键字以绘制分组直方图:
In [36]: data = pd.Series(np.random.randn(1000))
In [37]: data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4));
此外,还可以在DataFrame.plot.hist()
中指定by
关键字。
从版本 1.4.0 开始更改。
In [38]: data = pd.DataFrame(
....: {
....: "a": np.random.choice(["x", "y", "z"], 1000),
....: "b": np.random.choice(["e", "f", "g"], 1000),
....: "c": np.random.randn(1000),
....: "d": np.random.randn(1000) - 1,
....: },
....: )
....:
In [39]: data.plot.hist(by=["a", "b"], figsize=(10, 5));
### 箱线图
可以调用Series.plot.box()
和DataFrame.plot.box()
,或者DataFrame.boxplot()
来绘制箱线图,以可视化每列中的值的分布。
例如,这里是一个代表在[0,1)上的均匀随机变量的 10 次观测的五次试验的箱线图。
In [40]: df = pd.DataFrame(np.random.rand(10, 5), columns=["A", "B", "C", "D", "E"])
In [41]: df.plot.box();
通过传递color
关键字可以为箱线图着色。您可以传递一个dict
,其键为boxes
、whiskers
、medians
和caps
。如果dict
中缺少某些键,则对应的艺术家将使用默认颜色。此外,箱线图具有sym
关键字来指定离群值的样式。
当您通过color
关键字传递其他类型的参数时,它将直接传递给所有boxes
、whiskers
、medians
和caps
的着色。
颜色应用于要绘制的每个箱子。如果您想要更复杂的着色,可以通过传递 return_type 来获取每个绘制的图形。
In [42]: color = {
....: "boxes": "DarkGreen",
....: "whiskers": "DarkOrange",
....: "medians": "DarkBlue",
....: "caps": "Gray",
....: }
....:
In [43]: df.plot.box(color=color, sym="r+");
此外,您可以通过传递 matplotlib 支持的其他关键字来传递其他关键字。例如,通过vert=False
和positions
关键字可以绘制水平和自定义位置的箱线图。
In [44]: df.plot.box(vert=False, positions=[1, 4, 5, 6, 8]);
查看boxplot
方法和matplotlib boxplot 文档以获取更多信息。
仍然可以使用现有接口DataFrame.boxplot
来绘制箱线图。
In [45]: df = pd.DataFrame(np.random.rand(10, 5))
In [46]: plt.figure();
In [47]: bp = df.boxplot()
您可以使用by
关键字参数创建分组来创建分层箱线图。例如,
In [48]: df = pd.DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
In [49]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [50]: plt.figure();
In [51]: bp = df.boxplot(by="X")
您还可以传递要绘制的列的子集,以及按多个列分组:
In [52]: df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
In [53]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [54]: df["Y"] = pd.Series(["A", "B", "A", "B", "A", "B", "A", "B", "A", "B"])
In [55]: plt.figure();
In [56]: bp = df.boxplot(column=["Col1", "Col2"], by=["X", "Y"])
您还可以使用DataFrame.plot.box()
创建分组,例如:
在 1.4.0 版本中更改。
In [57]: df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
In [58]: df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
In [59]: plt.figure();
In [60]: bp = df.plot.box(column=["Col1", "Col2"], by="X")
��boxplot
中,返回类型可以通过return_type
关键字进行控制。有效选择为{"axes", "dict", "both", None}
。通过by
关键字创建的分面,将影响输出类型:
return_type |
分面 | 输出类型 |
---|---|---|
None |
否 | 坐标轴 |
None |
是 | 2-D 数组的坐标轴 |
'axes' |
否 | 坐标轴 |
'axes' |
是 | 坐标轴系列 |
'dict' |
否 | 艺术家的字典 |
'dict' |
是 | 艺术家的字典系列 |
'both' |
否 | 命名元组 |
'both' |
是 | 命名元组系列 |
Groupby.boxplot
总是返回一个return_type
的Series
。
In [61]: np.random.seed(1234)
In [62]: df_box = pd.DataFrame(np.random.randn(50, 2))
In [63]: df_box["g"] = np.random.choice(["A", "B"], size=50)
In [64]: df_box.loc[df_box["g"] == "B", 1] += 3
In [65]: bp = df_box.boxplot(by="g")
上面的子图首先按数值列分割,然后按g
列的值分割。下面的子图首先按g
的值分割,然后按数值列分割。
In [66]: bp = df_box.groupby("g").boxplot()
### 区域图
你可以使用Series.plot.area()
和DataFrame.plot.area()
创建区域图。默认情况下,区域图是堆叠的。要生成堆叠的区域图,每一列都必须是全部为正值或全部为负值。
当输入数据包含NaN
时,它将自动填充为 0。如果你想要删除或用不同的值填充,请在调用plot
之前使用dataframe.dropna()
或dataframe.fillna()
。
In [67]: df = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
In [68]: df.plot.area();
要生成未堆叠的图,请传递stacked=False
。除非另有说明,否则α值设为 0.5:
In [69]: df.plot.area(stacked=False);
### 散点图
散点图可通过使用DataFrame.plot.scatter()
方法绘制。散点图需要在 x 和 y 轴上具有数值列。这可以通过x
和y
关键字指定。
In [70]: df = pd.DataFrame(np.random.rand(50, 4), columns=["a", "b", "c", "d"])
In [71]: df["species"] = pd.Categorical(
....: ["setosa"] * 20 + ["versicolor"] * 20 + ["virginica"] * 10
....: )
....:
In [72]: df.plot.scatter(x="a", y="b");
要在单个坐标轴上绘制多个列组,请重复使用plot
方法指定目标ax
。建议指定color
和label
关键字以区分每个组。
In [73]: ax = df.plot.scatter(x="a", y="b", color="DarkBlue", label="Group 1")
In [74]: df.plot.scatter(x="c", y="d", color="DarkGreen", label="Group 2", ax=ax);
关键字c
可以作为一个列名给出,以为每个点提供颜色:
In [75]: df.plot.scatter(x="a", y="b", c="c", s=50);
如果向c
传递了一个分类列,则会产生一个离散的色彩条:
1.3.0 版本中的新功能。
In [76]: df.plot.scatter(x="a", y="b", c="species", cmap="viridis", s=50);
你可以传递由 matplotlib 支持的其他关键字scatter
。下面的示例显示了使用DataFrame
列作为气泡大小的气泡图。
In [77]: df.plot.scatter(x="a", y="b", s=df["c"] * 200);
请参阅scatter
方法和matplotlib scatter 文档了解更多信息。
六边形箱图
您可以使用 DataFrame.plot.hexbin()
创建六边形箱图。如果您的数据过于密集,无法单独绘制每个点,则六边形箱图可以作为散点图的有用替代。
In [78]: df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
In [79]: df["b"] = df["b"] + np.arange(1000)
In [80]: df.plot.hexbin(x="a", y="b", gridsize=25);
一个有用的关键字参数是gridsize
;它控制 x 方向上的六边形数量,默认为 100。更大的gridsize
意味着更多、更小的箱子。
默认情况下,计算每个 (x, y)
点周围的计数直方图。您可以通过将值传递给 C
和 reduce_C_function
参数来指定替代聚合。C
指定每个 (x, y)
点的值,reduce_C_function
是一个带有一个参数的函数,它将箱中的所有值缩减为一个单一的数字(例如 mean
、max
、sum
、std
)。在此示例中,位置由列 a
和 b
给出,而值由列 z
给出。箱子使用 NumPy 的 max
函数进行聚合。
In [81]: df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
In [82]: df["b"] = df["b"] + np.arange(1000)
In [83]: df["z"] = np.random.uniform(0, 3, 1000)
In [84]: df.plot.hexbin(x="a", y="b", C="z", reduce_C_function=np.max, gridsize=25);
请参阅hexbin
方法和matplotlib hexbin 文档了解更多信息。
饼图
您可以使用 DataFrame.plot.pie()
或 Series.plot.pie()
创建饼图。如果您的数据包含任何 NaN
,它们将自动填充为 0。如果数据中有任何负值,将引发 ValueError
。
In [85]: series = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"], name="series")
In [86]: series.plot.pie(figsize=(6, 6));
对于饼图,最好使用方形图形,即图形纵横比为 1。您可以创建等宽和等高的图形,或者在绘图后通过调用 ax.set_aspect('equal')
设置纵横比相等。
请注意,使用 DataFrame
创建的饼图需要通过 y
参数或 subplots=True
指定目标列。当指定了 y
,将绘制所选列的饼图。如果指定了 subplots=True
,将绘制每列的饼图子图。默认情况下,每个饼图中都会绘制图例;指定 legend=False
来隐藏它。
In [87]: df = pd.DataFrame(
....: 3 * np.random.rand(4, 2), index=["a", "b", "c", "d"], columns=["x", "y"]
....: )
....:
In [88]: df.plot.pie(subplots=True, figsize=(8, 4));
您可以使用 labels
和 colors
关键字指定每个楔形图的标签和颜色。
警告
大多数 pandas 绘图使用 label
和 color
参数(请注意这两个参数上没有“s”)。为了与 matplotlib.pyplot.pie()
保持一致,您必须使用 labels
和 colors
。
如果要隐藏楔形图标签,请指定 labels=None
。如果指定了 fontsize
,该值将应用于楔形图标签。还可以使用 matplotlib.pyplot.pie()
支持的其他关键字。
In [89]: series.plot.pie(
....: labels=["AA", "BB", "CC", "DD"],
....: colors=["r", "g", "b", "c"],
....: autopct="%.2f",
....: fontsize=20,
....: figsize=(6, 6),
....: );
....:
如果传入的值总和小于 1.0,则会重新缩放这些值,使其总和为 1。
In [90]: series = pd.Series([0.1] * 4, index=["a", "b", "c", "d"], name="series2")
In [91]: series.plot.pie(figsize=(6, 6));
更多内容请参阅 matplotlib 饼图文档。
绘制带缺失数据的图表
pandas 在绘制包含缺失数据的 DataFrame
或 Series
时会尝试保持实用性。根据绘图类型,缺失值会被删除、省略或填充。
绘图类型 | NaN 处理 |
---|---|
折线图 | 在 NaN 处留空隙 |
线条(堆叠) | 填充 0 值 |
条形图 | 填充 0 值 |
散点图 | 删除 NaN |
直方图 | 删除 NaN(列向) |
箱线图 | 删除 NaN(列向) |
区域 | 填充 0 值 |
KDE | 删除 NaN(列向) |
六边形图 | 删除 NaN |
饼图 | 填充 0 值 |
如果这些默认值不符合您的要求,或者如果您想明确指定如何处理缺失值,请考虑在绘图之前使用 fillna()
或 dropna()
。
绘图工具
这些函数可以从 pandas.plotting
中导入,并以 Series
或 DataFrame
作为参数。
散点矩阵图
您可以使用 pandas.plotting
中的 scatter_matrix
方法创建散点图矩阵:
In [92]: from pandas.plotting import scatter_matrix
In [93]: df = pd.DataFrame(np.random.randn(1000, 4), columns=["a", "b", "c", "d"])
In [94]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal="kde");
### 密度图
您可以使用 Series.plot.kde()
和 DataFrame.plot.kde()
方法创建密度图。
In [95]: ser = pd.Series(np.random.randn(1000))
In [96]: ser.plot.kde();
### 安德鲁斯曲线
Andrews 曲线允许将多变量数据绘制为大量曲线,这些曲线是使用样本属性作为傅立叶级数系数创建的,有关更多信息,请参阅Wikipedia 条目。通过为每个类别的曲线着不同颜色,可以可视化数据聚类。同一类别样本的曲线通常会更接近并形成更大的结构。
注意: “鸢尾花”数据集可在此处获取。
In [97]: from pandas.plotting import andrews_curves
In [98]: data = pd.read_csv("data/iris.data")
In [99]: plt.figure();
In [100]: andrews_curves(data, "Name");
### 平行坐标
平行坐标是一种用于绘制多变量数据的绘图技术,有关简介,请参阅Wikipedia 条目。平行坐标允许查看数据中的聚类并通过视觉估计其他统计量。使用平行坐标,点被表示为连接的线段。每条垂直线代表一个属性。一组连接的线段代表一个数据点。倾向于聚类的点将更接近。
In [101]: from pandas.plotting import parallel_coordinates
In [102]: data = pd.read_csv("data/iris.data")
In [103]: plt.figure();
In [104]: parallel_coordinates(data, "Name");
### 滞后图
滞后图用于检查数据集或时间序列是否随机。随机数据在滞后图中不应展现任何结构。非随机结构意味着底层数据不是随机的。可以传递lag
参数,当lag=1
时,图基本上是data[:-1]
vs. data[1:]
。
In [105]: from pandas.plotting import lag_plot
In [106]: plt.figure();
In [107]: spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)
In [108]: data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))
In [109]: lag_plot(data);
### 自相关图
自相关图通常用于检查时间序列中的随机性。这是通过计算不同时间滞后的数据值的自相关来实现的。如果时间序列是随机的,这些自相关应该在任何时间滞后分离上接近零。如果时间序列是非随机的,那么一个或多个自相关将显着非零。图中显示的水平线对应于 95%和 99%的置信区间。虚线是 99%的置信区间。有关自相关图的更多信息,请参阅Wikipedia 条目。
In [110]: from pandas.plotting import autocorrelation_plot
In [111]: plt.figure();
In [112]: spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
In [113]: data = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
In [114]: autocorrelation_plot(data);
### 自举图
自举图用于直观评估统计量(如均值、中位数、中程等)的不确定性。从数据集中选择指定大小的随机子集,为该子集计算所需的统计量,并重复指定次数。生成的图和直方图构成了自举图。
In [115]: from pandas.plotting import bootstrap_plot
In [116]: data = pd.Series(np.random.rand(1000))
In [117]: bootstrap_plot(data, size=50, samples=500, color="grey");
### RadViz
RadViz 是一种可视化多变量数据的方式。 它基于一种简单的弹簧张力最小化算法。 基本上,您在平面上设置一堆点。 在我们的案例中,它们在一个单位圆上等间距。 每个点表示一个单一属性。 然后,您假装数据集中的每个样本都通过弹簧连接到这些点,其中弹簧的刚度与该属性的数值成比例(它们被归一化为单位间隔)。 平面上我们的样本沉降到的点(作用于我们的样本的力处于平衡状态的地方)是我们的样本将被绘制的点。 根据该样本属于哪个类别,它将以不同的颜色着色。 有关更多信息,请参见 R 包Radviz。
注意: “鸢尾花”数据集可在此处找到。
In [118]: from pandas.plotting import radviz
In [119]: data = pd.read_csv("data/iris.data")
In [120]: plt.figure();
In [121]: radviz(data, "Name");
### 散点矩阵图
您可以使用pandas.plotting
中的scatter_matrix
方法创建散点图矩阵:
In [92]: from pandas.plotting import scatter_matrix
In [93]: df = pd.DataFrame(np.random.randn(1000, 4), columns=["a", "b", "c", "d"])
In [94]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal="kde");
### 密度图
您可以使用Series.plot.kde()
和DataFrame.plot.kde()
方法创建密度图。
In [95]: ser = pd.Series(np.random.randn(1000))
In [96]: ser.plot.kde();
### 安德鲁曲线
安德鲁曲线允许将多变量数据绘制为大量曲线,这些曲线是使用样本属性作为傅里叶级数的系数创建的,请参阅Wikipedia 词条获取更多信息。 通过为每个类别的曲线着色,可以可视化数据聚类。 属于相同类别样本的曲线通常会更接近并形成较大的结构。
注意: “鸢尾花”数据集可在此处找到。
In [97]: from pandas.plotting import andrews_curves
In [98]: data = pd.read_csv("data/iris.data")
In [99]: plt.figure();
In [100]: andrews_curves(data, "Name");
### 平行坐标
平行坐标是一种绘制多变量数据的绘图技术,请参阅Wikipedia 词条进行介绍。 平行坐标允许人们看到数据中的聚类并通过视觉估计其他统计数据。 使用平行坐标,点被表示为连接的线段。 每条垂直线代表一个属性。 一组连接的线段代表一个数据点。 倾向于聚类的点将出现在更接近的位置。
In [101]: from pandas.plotting import parallel_coordinates
In [102]: data = pd.read_csv("data/iris.data")
In [103]: plt.figure();
In [104]: parallel_coordinates(data, "Name");
### 滞后图
Lag plots 用于检查数据集或时间序列是否是随机的。随机数据不应在滞后图中展现任何结构。非随机结构意味着底层数据不是随机的。可以传递 lag
参数,当 lag=1
时,图基本上是 data[:-1]
对 data[1:]
。
In [105]: from pandas.plotting import lag_plot
In [106]: plt.figure();
In [107]: spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)
In [108]: data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))
In [109]: lag_plot(data);
### Autocorrelation plot
Autocorrelation plots 经常用于检查时间序列的随机性。这是通过计算不同时间滞后的数据值的自相关来完成的。如果时间序列是随机的,这样的自相关应该在任何时间滞后分隔上都接近零。如果时间序列是非随机的,则一个或多个自相关将显着非零。图中显示的水平线对应于 95% 和 99% 的置信区间。虚线是 99% 置信区间。参见 Wikipedia 条目 获取有关自相关图的更多信息。
In [110]: from pandas.plotting import autocorrelation_plot
In [111]: plt.figure();
In [112]: spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
In [113]: data = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
In [114]: autocorrelation_plot(data);
### Bootstrap plot
Bootstrap plots 用于直观评估统计量(如均值、中位数、中间范围等)的不确定性。从数据集中选择指定大小的随机子集,计算这个子集的统计量,然后重复这个过程指定次数。生成的图和直方图构成了 Bootstrap plot。
In [115]: from pandas.plotting import bootstrap_plot
In [116]: data = pd.Series(np.random.rand(1000))
In [117]: bootstrap_plot(data, size=50, samples=500, color="grey");
### RadViz
RadViz 是一种可视化多变量数据的方式。它基于简单的弹簧张力最小化算法。基本上,你在平面上设置了一堆点。在我们的案例中,它们在单位圆上等距分布。每个点代表一个单一的属性。然后,你假装数据集中的每个样本都通过弹簧与这些点之一相连,弹簧的刚度与该属性的数值成比例(它们被归一化为单位间隔)。平面上我们的样本停留的点(作用于我们的样本的力处于平衡状态的点)就是我们的样本将被绘制的点。取决于该样本属于哪个类,它将以不同的颜色着色。查看 R 包 Radviz 以获取更多信息。
注意: “鸢尾花”数据集可在此处获取。
In [118]: from pandas.plotting import radviz
In [119]: data = pd.read_csv("data/iris.data")
In [120]: plt.figure();
In [121]: radviz(data, "Name");
## Plot formatting
设置图样式
从 1.5 版本开始,matplotlib 提供了一系列预配置的绘图样式。设置样式可用于轻松地给出所需的一般外观。设置样式就像在创建绘图之前调用matplotlib.style.use(my_plot_style)
一样简单。例如,您可以写matplotlib.style.use('ggplot')
以获得 ggplot 风格的绘图。
你可以在matplotlib.style.available
中看到各种可用的样式名称,很容易尝试它们。
一般绘图样式参数
大多数绘图方法都有一组关键字参数,用于控制返回图的布局和格式:
In [122]: plt.figure();
In [123]: ts.plot(style="k--", label="Series");
对于每种类型的绘图(例如line
,bar
,scatter
),任何额外的参数关键字都会传递给相应的 matplotlib 函数(ax.plot()
, ax.bar()
, ax.scatter()
). 这些可以用于控制额外的样式,超出 pandas 提供的范围。
控制图例
您可以将legend
参数设置为False
以隐藏默认显示的图例。
In [124]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [125]: df = df.cumsum()
In [126]: df.plot(legend=False);
控制标签
您可以设置xlabel
和ylabel
参数,为 x 和 y 轴提供自定义标签。默认情况下,pandas 将选择索引名称作为 xlabel,同时将其留空作为 ylabel。
In [127]: df.plot();
In [128]: df.plot(xlabel="new x", ylabel="new y");
刻度
您可以传递logy
以获得对数刻度 Y 轴。
In [129]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [130]: ts = np.exp(ts.cumsum())
In [131]: ts.plot(logy=True);
另请参阅logx
和loglog
关键字参数。
在第二个 y 轴上绘图
要在第二个 y 轴上绘制数据,请使用secondary_y
关键字:
In [132]: df["A"].plot();
In [133]: df["B"].plot(secondary_y=True, style="g");
要在DataFrame
中绘制一些列,请将列名提供给secondary_y
关键字:
In [134]: plt.figure();
In [135]: ax = df.plot(secondary_y=["A", "B"])
In [136]: ax.set_ylabel("CD scale");
In [137]: ax.right_ax.set_ylabel("AB scale");
请注意,在第二个 y 轴上绘制的列会自动在图例中标记为“(right)”。要关闭自动标记,请使用mark_right=False
关键字:
In [138]: plt.figure();
In [139]: df.plot(secondary_y=["A", "B"], mark_right=False);
### 时间序列绘图的自定义格式化程序
pandas 为时间序列图提供自定义格式化程序。这些更改日期和时间的轴标签格式。默认情况下,自定义格式化程序仅应用于由 pandas 使用DataFrame.plot()
或Series.plot()
创建的图。要使它们应用于所有图,包括由 matplotlib 创建的图,请设置选项pd.options.plotting.matplotlib.register_converters = True
或使用pandas.plotting.register_matplotlib_converters()
。
抑制刻度分辨率调整
pandas 包括对常规频率时间序列数据的自动刻度分辨率调整。对于 pandas 无法推断频率信息的有限情况(例如,在外部创建的twinx
中),您可以选择抑制此行为以进行对齐。
这是默认行为,请注意 x 轴刻度标签的处理方式:
In [140]: plt.figure();
In [141]: df["A"].plot();
使用x_compat
参数,可以抑制这种行为:
In [142]: plt.figure();
In [143]: df["A"].plot(x_compat=True);
如果有多个需要抑制的图,可以在pandas.plotting.plot_params
中使用use
方法,并在with
语句中使用:
In [144]: plt.figure();
In [145]: with pd.plotting.plot_params.use("x_compat", True):
.....: df["A"].plot(color="r")
.....: df["B"].plot(color="g")
.....: df["C"].plot(color="b")
.....:
自动日期刻度调整
TimedeltaIndex
现在使用本机 matplotlib 刻度定位器方法,对于刻度标签重叠的图形,调用 matplotlib 的自动日期刻度调整非常有用。
查看autofmt_xdate
方法和matplotlib 文档以获取更多信息。
子图
DataFrame
中的每个Series
可以使用subplots
关键字在不同的轴上绘制:
In [146]: df.plot(subplots=True, figsize=(6, 6));
使用布局和定位多个轴
子图的布局可以由layout
关键字指定。它可以接受(行数, 列数)
。layout
关键字也可以在hist
和boxplot
中使用。如果输入无效,将引发ValueError
。
由layout
指定的行 x 列中可以包含的轴的数量必须大于所需子图的数量。如果layout
可以包含比所需更多的轴,那么空白轴将不会被绘制。类似于 NumPy 数组的reshape
方法,您可以在一个维度上使用-1
来自动计算所需的行数或列数,给定另一个维度。
In [147]: df.plot(subplots=True, layout=(2, 3), figsize=(6, 6), sharex=False);
上面的示例与使用以下内容相同:
In [148]: df.plot(subplots=True, layout=(2, -1), figsize=(6, 6), sharex=False);
所需的列数(3)是从要绘制的系列数和给定的行数(2)推断出来的。
您可以通过ax
关键字以类似列表的方式传递预先创建的多个轴。这允许更复杂的布局。传递的轴数量必须与正在绘制的子图数量相同。
当通过ax
关键字传递多个轴时,layout
、sharex
和sharey
关键字不会影响输出。您应该明确传递sharex=False
和sharey=False
,否则会看到警告。
In [149]: fig, axes = plt.subplots(4, 4, figsize=(9, 9))
In [150]: plt.subplots_adjust(wspace=0.5, hspace=0.5)
In [151]: target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]]
In [152]: target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]]
In [153]: df.plot(subplots=True, ax=target1, legend=False, sharex=False, sharey=False);
In [154]: (-df).plot(subplots=True, ax=target2, legend=False, sharex=False, sharey=False);
另一个选项是将ax
参数传递给Series.plot()
以在特定轴上绘制:
In [155]: np.random.seed(123456)
In [156]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [157]: ts = ts.cumsum()
In [158]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [159]: df = df.cumsum()
In [160]: fig, axes = plt.subplots(nrows=2, ncols=2)
In [161]: plt.subplots_adjust(wspace=0.2, hspace=0.5)
In [162]: df["A"].plot(ax=axes[0, 0]);
In [163]: axes[0, 0].set_title("A");
In [164]: df["B"].plot(ax=axes[0, 1]);
In [165]: axes[0, 1].set_title("B");
In [166]: df["C"].plot(ax=axes[1, 0]);
In [167]: axes[1, 0].set_title("C");
In [168]: df["D"].plot(ax=axes[1, 1]);
In [169]: axes[1, 1].set_title("D");
### 带有误差条的绘图
支持在DataFrame.plot()
和Series.plot()
中绘制带有误差条的图。
水平和垂直误差条可以通过xerr
和yerr
关键字参数提供给plot()
。误差值可以使用各种格式指定:
-
作为一个
DataFrame
或与绘图DataFrame
的columns
属性匹配或与Series
的name
属性匹配的错误dict
。 -
作为一个
str
,指示绘图DataFrame
的哪些列包含错误值。 -
作为原始值(
list
、tuple
或np.ndarray
)。必须与绘图DataFrame
/Series
的长度相同。
这是一个从原始数据轻松绘制组均值和标准差的示例。
# Generate the data
In [170]: ix3 = pd.MultiIndex.from_arrays(
.....: [
.....: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
.....: ["foo", "foo", "foo", "bar", "bar", "foo", "foo", "bar", "bar", "bar"],
.....: ],
.....: names=["letter", "word"],
.....: )
.....:
In [171]: df3 = pd.DataFrame(
.....: {
.....: "data1": [9, 3, 2, 4, 3, 2, 4, 6, 3, 2],
.....: "data2": [9, 6, 5, 7, 5, 4, 5, 6, 5, 1],
.....: },
.....: index=ix3,
.....: )
.....:
# Group by index labels and take the means and standard deviations
# for each group
In [172]: gp3 = df3.groupby(level=("letter", "word"))
In [173]: means = gp3.mean()
In [174]: errors = gp3.std()
In [175]: means
Out[175]:
data1 data2
letter word
a bar 3.500000 6.000000
foo 4.666667 6.666667
b bar 3.666667 4.000000
foo 3.000000 4.500000
In [176]: errors
Out[176]:
data1 data2
letter word
a bar 0.707107 1.414214
foo 3.785939 2.081666
b bar 2.081666 2.645751
foo 1.414214 0.707107
# Plot
In [177]: fig, ax = plt.subplots()
In [178]: means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
也支持不对称误差条,但在这种情况下必须提供原始误差值。对于长度为N
的Series
,应提供一个2xN
数组,指示较低和较高(或左侧和右侧)的错误。对于MxN``DataFrame
,不对称误差应该在一个Mx2xN
数组中。
这是一个使用不对称误差条绘制最小/最大范围的示例。
In [179]: mins = gp3.min()
In [180]: maxs = gp3.max()
# errors should be positive, and defined in the order of lower, upper
In [181]: errors = [[means[c] - mins[c], maxs[c] - means[c]] for c in df3.columns]
# Plot
In [182]: fig, ax = plt.subplots()
In [183]: means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
### 绘制表格
现在在DataFrame.plot()
和Series.plot()
中支持使用table
关键字绘制 matplotlib 表格。table
关键字可以接受bool
、DataFrame
或Series
。绘制表格的简单方法是指定table=True
。数据将被转置以符合 matplotlib 的默认布局。
In [184]: np.random.seed(123456)
In [185]: fig, ax = plt.subplots(1, 1, figsize=(7, 6.5))
In [186]: df = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
In [187]: ax.xaxis.tick_top() # Display x-axis ticks on top.
In [188]: df.plot(table=True, ax=ax);
此外,您可以将不同的DataFrame
或Series
传递给table
关键字。数据将按照打印方法中显示的方式绘制(不会自动转置)。如果需要,可以像下面的示例中所示手动转置。
In [189]: fig, ax = plt.subplots(1, 1, figsize=(7, 6.75))
In [190]: ax.xaxis.tick_top() # Display x-axis ticks on top.
In [191]: df.plot(table=np.round(df.T, 2), ax=ax);
还存在一个辅助函数pandas.plotting.table
,它可以从DataFrame
或Series
创建表格,并将其添加到matplotlib.Axes
实例中。此函数可以接受 matplotlib table的关键字。
In [192]: from pandas.plotting import table
In [193]: fig, ax = plt.subplots(1, 1)
In [194]: table(ax, np.round(df.describe(), 2), loc="upper right", colWidths=[0.2, 0.2, 0.2]);
In [195]: df.plot(ax=ax, ylim=(0, 2), legend=None);
注意:您可以使用axes.tables
属性在坐标轴上获取表实例以进行进一步装饰。更多信息请参阅matplotlib 表格文档。### 颜色映射
在绘制大量列时可能会遇到一个潜在问题,即由于默认颜色中的重复,有些系列很难区分。为了解决这个问题,DataFrame
绘图支持使用colormap
参数,该参数接受 Matplotlib 的颜色映射或 Matplotlib 注册的颜色映射名称的字符串。可以在这里查看默认 matplotlib 颜色映射的可视化。
由于 matplotlib 不直接支持基于线条的绘图的颜色映射,颜色是根据DataFrame
中的列数确定的均匀间距选择的。不考虑背景颜色,因此某些颜色映射会产生不易看清的线条。
要使用 cubehelix 颜色映射,我们可以传递colormap='cubehelix'
。
In [196]: np.random.seed(123456)
In [197]: df = pd.DataFrame(np.random.randn(1000, 10), index=ts.index)
In [198]: df = df.cumsum()
In [199]: plt.figure();
In [200]: df.plot(colormap="cubehelix");
或者,我们可以直接传递颜色映射本身:
In [201]: from matplotlib import cm
In [202]: plt.figure();
In [203]: df.plot(colormap=cm.cubehelix);
颜色映射也可以用于其他绘图类型,比如条形图:
In [204]: np.random.seed(123456)
In [205]: dd = pd.DataFrame(np.random.randn(10, 10)).map(abs)
In [206]: dd = dd.cumsum()
In [207]: plt.figure();
In [208]: dd.plot.bar(colormap="Greens");
平行坐标图:
In [209]: plt.figure();
In [210]: parallel_coordinates(data, "Name", colormap="gist_rainbow");
Andrews 曲线图:
In [211]: plt.figure();
In [212]: andrews_curves(data, "Name", colormap="winter");
设置绘图样式
从版本 1.5 开始,matplotlib 提供了一系列预配置的绘图样式。设置样式可以轻松地使绘图具有您想要的一般外观。在创建绘图之前调用matplotlib.style.use(my_plot_style)
就可以设置样式。例如,您可以写matplotlib.style.use('ggplot')
来获得 ggplot 风格的绘图。
您可以查看matplotlib.style.available
中提供的各种样式名称,并且非常容易尝试它们。
一般绘图样式参数
大多数绘图方法都有一组关键字参数��用于控制返回绘图的布局和格式:
In [122]: plt.figure();
In [123]: ts.plot(style="k--", label="Series");
对于每种类型的绘图(例如line
,bar
,scatter
),任何额外的参数关键字都会传递给相应的 matplotlib 函数(ax.plot()
, ax.bar()
, ax.scatter()
). 这些参数可以用于控制额外的样式,超出 pandas 提供的范围。
控制图例
您可以将legend
参数设置为False
以隐藏图例,默认情况下会显示图例。
In [124]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [125]: df = df.cumsum()
In [126]: df.plot(legend=False);
控制标签
您可以设置xlabel
和ylabel
参数,为 x 轴和 y 轴提供自定义标签。默认情况下,pandas 会选择索引名称作为 xlabel,而将其留空作为 ylabel。
In [127]: df.plot();
In [128]: df.plot(xlabel="new x", ylabel="new y");
刻度
您可以传递logy
以获得对数刻度 Y 轴。
In [129]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [130]: ts = np.exp(ts.cumsum())
In [131]: ts.plot(logy=True);
还可以查看logx
和loglog
关键字参数。
在次要 y 轴上绘图
要在次要 y 轴上绘制数据,请使用secondary_y
关键字:
In [132]: df["A"].plot();
In [133]: df["B"].plot(secondary_y=True, style="g");
要在DataFrame
中绘制一些列,请将列名传递给secondary_y
关键字:
In [134]: plt.figure();
In [135]: ax = df.plot(secondary_y=["A", "B"])
In [136]: ax.set_ylabel("CD scale");
In [137]: ax.right_ax.set_ylabel("AB scale");
请注意,在次要 y 轴上绘制的列会在图例中自动标记为“(right)”。要关闭自动标记,使用mark_right=False
关键字:
In [138]: plt.figure();
In [139]: df.plot(secondary_y=["A", "B"], mark_right=False);
### 时间序列图的自定义格式化程序
pandas 为时间序列图提供了自定义格式化程序。这些更改日期和时间的轴标签格式。默认情况下,自定义格式化程序仅应用于由 pandas 使用DataFrame.plot()
或Series.plot()
创建的图。要使其应用于所有图,包括由 matplotlib 创建的图,请设置选项pd.options.plotting.matplotlib.register_converters = True
或使用pandas.plotting.register_matplotlib_converters()
。
抑制刻度分辨率调整
pandas 为常规频率时间序列数据提供自动刻度分辨率调整。对于 pandas 无法推断频率信息的有限情况(例如,在外部创建的twinx
中),您可以选择抑制此行为以进行对齐。
这是默认行为,请注意 x 轴刻度标签的处理方式:
In [140]: plt.figure();
In [141]: df["A"].plot();
使用x_compat
参数,您可以抑制此行为:
In [142]: plt.figure();
In [143]: df["A"].plot(x_compat=True);
如果有多个需要抑制的图,可以在pandas.plotting.plot_params
中使用use
方法,并在with
语句中使用:
In [144]: plt.figure();
In [145]: with pd.plotting.plot_params.use("x_compat", True):
.....: df["A"].plot(color="r")
.....: df["B"].plot(color="g")
.....: df["C"].plot(color="b")
.....:
自动日期刻度调整
TimedeltaIndex
现在使用本机 matplotlib 刻度定位器方法,对于刻度标签重叠的图形,调用 matplotlib 的自动日期刻度调整非常有用。
有关更多信息,请参阅autofmt_xdate
方法和matplotlib 文档。
子图
DataFrame
中的每个Series
都可以使用subplots
关键字绘制在不同的轴上:
In [146]: df.plot(subplots=True, figsize=(6, 6));
使用布局和定位多个轴
子图的布局可以通过layout
关键字指定。它可以接受(行数, 列数)
。layout
关键字也可以在hist
和boxplot
中使用。如果输入无效,将引发ValueError
。
通过layout
指定的行 x 列所包含的轴的数量必须大于所需子图的数量。如果布局可以包含比所需更多的轴,则不会绘制空白轴。类似于 NumPy 数组的reshape
方法,您可以在一个维度上使用-1
来自动计算所需的行数或列数,给定另一个维度。
In [147]: df.plot(subplots=True, layout=(2, 3), figsize=(6, 6), sharex=False);
上述示例与使用以下内容相同:
In [148]: df.plot(subplots=True, layout=(2, -1), figsize=(6, 6), sharex=False);
所需的列数(3)是从要绘制的系列数和给定的行数(2)推断出来的。
您可以通过ax
关键字以类似列表的方式传递预先创建的多个轴。这允许更复杂的布局。传递的轴数量必须与正在绘制的子图数量相同。
通过ax
关键字传递多个轴时,layout
、sharex
和sharey
关键字不会影响输出。您应该明确传递sharex=False
和sharey=False
,否则会看到警告。
In [149]: fig, axes = plt.subplots(4, 4, figsize=(9, 9))
In [150]: plt.subplots_adjust(wspace=0.5, hspace=0.5)
In [151]: target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]]
In [152]: target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]]
In [153]: df.plot(subplots=True, ax=target1, legend=False, sharex=False, sharey=False);
In [154]: (-df).plot(subplots=True, ax=target2, legend=False, sharex=False, sharey=False);
另一个选项是通过在Series.plot()
中传递一个ax
参数来在特定轴上绘图:
In [155]: np.random.seed(123456)
In [156]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
In [157]: ts = ts.cumsum()
In [158]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
In [159]: df = df.cumsum()
In [160]: fig, axes = plt.subplots(nrows=2, ncols=2)
In [161]: plt.subplots_adjust(wspace=0.2, hspace=0.5)
In [162]: df["A"].plot(ax=axes[0, 0]);
In [163]: axes[0, 0].set_title("A");
In [164]: df["B"].plot(ax=axes[0, 1]);
In [165]: axes[0, 1].set_title("B");
In [166]: df["C"].plot(ax=axes[1, 0]);
In [167]: axes[1, 0].set_title("C");
In [168]: df["D"].plot(ax=axes[1, 1]);
In [169]: axes[1, 1].set_title("D");
### 带有误差条的绘图
在DataFrame.plot()
和Series.plot()
中支持带有误差条的绘图。
水平和垂直误差条可以通过xerr
和yerr
关键字参数传递给plot()
。误差值可以使用各种格式指定:
-
作为
DataFrame
或与绘图DataFrame
的columns
属性匹配或与Series
的name
属性匹配的错误的dict
。 -
作为一个
str
,指示绘图DataFrame
中包含误差值的列。 -
作为原始值(
list
、tuple
或np.ndarray
)。必须与绘图DataFrame
/Series
的长度相同。
这是一个从原始数据轻松绘制组均值和标准差的示例方法。
# Generate the data
In [170]: ix3 = pd.MultiIndex.from_arrays(
.....: [
.....: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
.....: ["foo", "foo", "foo", "bar", "bar", "foo", "foo", "bar", "bar", "bar"],
.....: ],
.....: names=["letter", "word"],
.....: )
.....:
In [171]: df3 = pd.DataFrame(
.....: {
.....: "data1": [9, 3, 2, 4, 3, 2, 4, 6, 3, 2],
.....: "data2": [9, 6, 5, 7, 5, 4, 5, 6, 5, 1],
.....: },
.....: index=ix3,
.....: )
.....:
# Group by index labels and take the means and standard deviations
# for each group
In [172]: gp3 = df3.groupby(level=("letter", "word"))
In [173]: means = gp3.mean()
In [174]: errors = gp3.std()
In [175]: means
Out[175]:
data1 data2
letter word
a bar 3.500000 6.000000
foo 4.666667 6.666667
b bar 3.666667 4.000000
foo 3.000000 4.500000
In [176]: errors
Out[176]:
data1 data2
letter word
a bar 0.707107 1.414214
foo 3.785939 2.081666
b bar 2.081666 2.645751
foo 1.414214 0.707107
# Plot
In [177]: fig, ax = plt.subplots()
In [178]: means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
不对称误差条也受支持,但在这种情况下必须提供原始误差值。对于长度为N
的Series
,应提供一个2xN
数组,指示下限和上限(或左侧和右侧)误差。对于MxN
的DataFrame
,不对称误差应该是一个Mx2xN
数组。
这是使用不对称误差线绘制最小/最大范围的一种方法示例。
In [179]: mins = gp3.min()
In [180]: maxs = gp3.max()
# errors should be positive, and defined in the order of lower, upper
In [181]: errors = [[means[c] - mins[c], maxs[c] - means[c]] for c in df3.columns]
# Plot
In [182]: fig, ax = plt.subplots()
In [183]: means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
### 绘制表格
使用 matplotlib 表格绘图现在在DataFrame.plot()
和Series.plot()
中支持table
关键字。table
关键字可以接受bool
、DataFrame
或Series
。绘制表格的简单方法是指定table=True
。数据将被转置以符合 matplotlib 的默认布局。
In [184]: np.random.seed(123456)
In [185]: fig, ax = plt.subplots(1, 1, figsize=(7, 6.5))
In [186]: df = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
In [187]: ax.xaxis.tick_top() # Display x-axis ticks on top.
In [188]: df.plot(table=True, ax=ax);
此外,您可以将不同的DataFrame
或Series
传递给table
关键字。数据将按照打印方法中显示的方式绘制(不会自动转置)。如果需要,可以像下面的示例中所示手动转置。
In [189]: fig, ax = plt.subplots(1, 1, figsize=(7, 6.75))
In [190]: ax.xaxis.tick_top() # Display x-axis ticks on top.
In [191]: df.plot(table=np.round(df.T, 2), ax=ax);
还有一个辅助函数pandas.plotting.table
,它可以从DataFrame
或Series
创建表格,并将其添加到matplotlib.Axes
实例中。此函数可以接受 matplotlib table具有的关键字。
In [192]: from pandas.plotting import table
In [193]: fig, ax = plt.subplots(1, 1)
In [194]: table(ax, np.round(df.describe(), 2), loc="upper right", colWidths=[0.2, 0.2, 0.2]);
In [195]: df.plot(ax=ax, ylim=(0, 2), legend=None);
注意:您可以使用axes.tables
属性在轴上获取表格实例以进行进一步装饰。更多信息请参阅matplotlib 表格文档。
色图
在绘制大量列时可能存在的一个问题是,由于默认颜色的重复,有些系列很难区分。为了解决这个问题,DataFrame
绘图支持使用colormap
参数,该参数接受 Matplotlib colormap或注册到 Matplotlib 的调色板名称的字符串。默认 matplotlib 调色板的可视化在这里。
由于 matplotlib 不直接支持基于线条的图形的调色板,颜色是根据DataFrame
中的列数确定的均匀间距选择的。没有考虑背景颜色,因此某些调色板会产生不易看清的线条。
要使用 cubehelix 调色板,我们可以传递colormap='cubehelix'
。
In [196]: np.random.seed(123456)
In [197]: df = pd.DataFrame(np.random.randn(1000, 10), index=ts.index)
In [198]: df = df.cumsum()
In [199]: plt.figure();
In [200]: df.plot(colormap="cubehelix");
或者,我们可以直接传递调色板本身:
In [201]: from matplotlib import cm
In [202]: plt.figure();
In [203]: df.plot(colormap=cm.cubehelix);
调色板也可以用于其他绘图类型,比如条形图:
In [204]: np.random.seed(123456)
In [205]: dd = pd.DataFrame(np.random.randn(10, 10)).map(abs)
In [206]: dd = dd.cumsum()
In [207]: plt.figure();
In [208]: dd.plot.bar(colormap="Greens");
平行坐标图表:
In [209]: plt.figure();
In [210]: parallel_coordinates(data, "Name", colormap="gist_rainbow");
安德鲁斯曲线图表:
In [211]: plt.figure();
In [212]: andrews_curves(data, "Name", colormap="winter");
直接使用 Matplotlib 绘图
在某些情况下,直接使用 matplotlib 准备图形可能仍然更可取或必要,例如当某种类型的图形或自定义尚未得到 pandas 的支持时。Series
和 DataFrame
对象的行为类似于数组,因此可以直接传递给 matplotlib 函数,无需显式转换。
pandas 还会自动注册识别日期索引的格式化程序和定位器,从而将日期和时间支持扩展到 matplotlib 中几乎所有可用的绘图类型。虽然这种格式化不提供通过 pandas 绘图时所获得的相同精细程度,但在绘制大量点时可能更快。
In [213]: np.random.seed(123456)
In [214]: price = pd.Series(
.....: np.random.randn(150).cumsum(),
.....: index=pd.date_range("2000-1-1", periods=150, freq="B"),
.....: )
.....:
In [215]: ma = price.rolling(20).mean()
In [216]: mstd = price.rolling(20).std()
In [217]: plt.figure();
In [218]: plt.plot(price.index, price, "k");
In [219]: plt.plot(ma.index, ma, "b");
In [220]: plt.fill_between(mstd.index, ma - 2 * mstd, ma + 2 * mstd, color="b", alpha=0.2);
绘图后端
pandas 可以通过第三方绘图后端进行扩展。主要思想是让用户选择一个不同于基于 Matplotlib 提供的后端的绘图后端。
这可以通过在plot
函数中将‘backend.module’作为参数backend
传递来实现。例如:
>>> Series([1, 2, 3]).plot(backend="backend.module")
或者,您也可以全局设置此选项,这样您就不需要在每个plot
调用中指定关键字。例如:
>>> pd.set_option("plotting.backend", "backend.module")
>>> pd.Series([1, 2, 3]).plot()
或者:
>>> pd.options.plotting.backend = "backend.module"
>>> pd.Series([1, 2, 3]).plot()
这将更或多少等同于:
>>> import backend.module
>>> backend.module.plot(pd.Series([1, 2, 3]))
然后,后端模块可以使用其他可视化工具(Bokeh、Altair、hvplot 等)生成图形。一些为 pandas 实现后端的库列在生态系统页面上。
开发者指南可在 pandas.pydata.org/docs/dev/development/extending.html#plotting-backends
找到。
表格可视化
本节演示使用 Styler 类可视化表格数据。有关使用图表进行可视化的信息,请参阅图表可视化。本文档是以 Jupyter Notebook 编写的,可在此处查看或下载这里。
Styler 对象和自定义显示
样式和输出显示定制应在对数据框中的数据进行处理之后执行。如果对数据框进行进一步更改,Styler不会动态更新。DataFrame.style
属性是一个返回 Styler 对象的属性。它在其上定义了一个_repr_html_
方法,因此在 Jupyter Notebook 中会自动呈现。
Styler,可用于大数据,但主要设计用于小数据,目前具有输出到以下格式的功能:
-
HTML
-
LaTeX
-
字符串(以及 CSV 扩展)
-
Excel
-
(JSON 目前不可用)
这些中的前三个具有设计用于格式化和自定义输出的显示定制方法。这些方法包括:
-
格式化数值、索引和列标题,使用.format()和.format_index(),
-
重命名索引或列标题标签,使用.relabel_index()
-
隐藏某些列、索引和/或列标题,或索引名称,使用.hide()
-
连接相似的数据框,使用.concat()
格式化显示
格式化数值
Styler 将显示值与实际值区分开,无论是数据值还是索引或列标题。为了控制显示值,文本在每个单元格中以字符串形式打印,我们可以使用.format()和.format_index()方法根据格式规范字符串或接受单个值并返回字符串的可调用对象来操作这一点。可以为整个表格、索引或单独的列或 MultiIndex 级别定义此操作。我们还可以覆盖索引名称。
此外,格式化函数具有 精度 参数,专门用于帮助格式化浮点数,以及 小数 和 千位分隔符 以支持其他语言环境,一个 na_rep 参数用于显示缺失数据,以及一个 escape 和 hyperlinks 参数用于帮助显示安全的 HTML 或安全的 LaTeX。默认格式化程序配置为采用 pandas 的全局选项,如 styler.format.precision
选项,可使用 with pd.option_context('format.precision', 2):
进行控制。
[2]:
import pandas as pd
import numpy as np
import matplotlib as mpl
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)
[2]:
字符串 | 整数 | 浮点数 | |
---|---|---|---|
第一行 | 亚当 | 1 | 1,123 |
第二行 | 迈克 | 3 | 1,000.230 |
使用 Styler 来操纵显示是一个有用的功能,因为保持索引和数据值用于其他目的可以提供更大的控制。您不必覆盖 DataFrame 来按照自己的喜好显示它。以下是一个更全面的示例,展示了在仍依赖底层数据进行索引和计算的情况下使用格式化函数。
[3]:
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
[3]:
东京 | 北京 | |
---|---|---|
2021-01-01 | 2.552517 | 1.976602 |
2021-01-02 | 1.665753 | 3.757927 |
2021-01-03 | 4.679882 | 2.242228 |
2021-01-04 | 1.268592 | 0.915911 |
2021-01-05 | 0.258386 | 4.647607 |
2021-01-06 | 1.279295 | 4.642458 |
2021-01-07 | 0.560487 | 3.670073 |
2021-01-08 | 0.980423 | 1.026641 |
2021-01-09 | 1.471664 | 1.384219 |
2021-01-10 | 4.617766 | 4.251794 |
[4]:
weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
[4]:
天气状况
东京 | 北京 | |
---|---|---|
星期一 | 干燥 | 干燥 |
星期二 | 干燥 | 大雨 |
星期三 | 干燥 | 大雨 |
星期四 | 干燥 | 大雨 |
星期五 | 干燥 | 干燥 |
隐藏数据
索引和列标题可以完全隐藏,也可以选择要排除的行或列。这两个选项使用相同的方法执行。
可以通过调用 .hide() 而不带任何参数来隐藏索引以便渲染,如果您的索引是基于整数的,这可能很有用。同样,通过调用 .hide(axis=”columns”) 而不带任何其他参数可以隐藏列标题。
可以通过调用相同的 .hide() 方法并传入行/列标签、类似列表或行/列标签的切片来隐藏特定行或列以便渲染。
隐藏不会改变 CSS 类的整数排列,例如,隐藏 DataFrame 的前两列意味着列类索引仍将从 col2
开始,因为 col0
和 col1
简单地被忽略。
[5]:
df = pd.DataFrame(np.random.randn(5, 5))
df.style \
.hide(subset=[0, 2, 4], axis=0) \
.hide(subset=[0, 2, 4], axis=1)
[5]:
1 | 3 | |
---|---|---|
1 | 0.561440 | -0.858225 |
3 | 0.176255 | 0.876609 |
要将功能反转为 显示 功能,最佳实践是组成一个隐藏项目的列表。
[6]:
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)
[6]:
0 | 2 | 4 | |
---|---|---|---|
0 | -0.056334 | -1.188982 | 0.482870 |
2 | -0.718731 | -0.499113 | -1.350023 |
4 | -0.720169 | 1.225336 | -0.512159 |
连接 DataFrame 输出
可以将两个或更多个样式化器连接在一起,前提是它们共享相同的列。这对于显示 DataFrame 的摘要统计信息非常有用,并经常与 DataFrame.agg 结合使用。
由于连接的对象是样式化器,它们可以独立进行样式设置,如下所示,它们的连接保留了这些样式。
[7]:
summary_styler = df.agg(["sum", "mean"]).style \
.format(precision=3) \
.relabel_index(["Sum", "Average"])
df.style.format(precision=1).concat(summary_styler)
[7]:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | -0.1 | 0.8 | -1.2 | 0.3 | 0.5 |
1 | 0.5 | 0.6 | 0.1 | -0.9 | 0.9 |
2 | -0.7 | -0.8 | -0.5 | 0.2 | -1.4 |
3 | 2.2 | 0.2 | 0.9 | 0.9 | 0.1 |
4 | -0.7 | -1.0 | 1.2 | -0.5 | -0.5 |
总和 | 1.179 | -0.213 | 0.506 | -0.082 | -0.430 |
平均值 | 0.236 | -0.043 | 0.101 | -0.016 | -0.086 |
样式化器对象和 HTML
样式化器最初是为了支持各种 HTML 格式选项而构建的。它的 HTML 输出创建了一个 HTML <table>
,并利用 CSS 样式语言来操纵许多参数,包括颜色、字体、边框、背景等。查看这里获取有关样式化 HTML 表格的更多信息。这使得在开箱即用的情况下具有很大的灵活性,甚至使 Web 开发人员能够将 DataFrame 集成到他们现有的用户界面设计中。
下面我们展示默认输出,看起来非常类似于标准 DataFrame HTML 表示。但是这里的 HTML 已经为每个单元格附加了一些 CSS 类,即使我们还没有创建任何样式。我们可以通过调用.to_html()方法来查看这些,该方法返回原始 HTML 字符串,这对于进一步处理或添加到文件中非常有用 - 请继续阅读有关 CSS 和 HTML 的更多信息。本节还将提供如何将此默认输出转换为更具沟通性的 DataFrame 输出的演示。例如我们如何构建s
:
[8]:
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
[8]:
| 模型: | 决策树 | 回归 | 随机 |
| --- | --- | --- |
预测: | 肿瘤 | 非肿瘤 | 肿瘤 | 非肿瘤 | 肿瘤 | 非肿瘤 |
---|---|---|---|---|---|---|
实际标签: | ||||||
--- | --- | --- | --- | --- | --- | --- |
肿瘤(阳性) | 38.000000 | 2.000000 | 18.000000 | 22.000000 | 21 | nan |
非肿瘤(阴性) | 19.000000 | 439.000000 | 6.000000 | 452.000000 | 226 | 232.000000 |
[10]:
s
[10]:
多个癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
我们采取的第一步是从 DataFrame 创建 Styler 对象,然后通过使用.hide()隐藏不需要的列来选择感兴趣的范围。
[11]:
s = df.style.format('{:.0f}').hide([('Random', 'Tumour'), ('Random', 'Non-Tumour')], axis="columns")
s
[11]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
添加样式的方法
有3 种主要方法可以向 Styler 添加自定义 CSS 样式:
-
使用.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 字符串,例如:
[13]:
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])
[13]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
接下来,我们只需添加几个针对表格特定部分的样式化元素。在这里要小心,因为我们正在链接方法,我们需要明确指示方法不要覆盖
现有样式。
[15]:
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)
[15]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
作为一个便利方法(自版本 1.2.0 起),我们还可以将一个字典传递给.set_table_styles(),其中包含行或列键。在幕后,Styler 只是索引键并根据需要向给定的 CSS 选择器添加相关的.col<m>
或.row<n>
类。
[17]:
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)
[17]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
设置类和链接到外部 CSS
如果您设计了一个网站,那么很可能您已经有一个控制其中表格和单元格对象样式的外部 CSS 文件。您可能希望使用这些原生文件,而不是在 Python 中重复所�� CSS(和重复任何维护工作)。
表属性
使用.set_table_attributes()非常容易向主<table>
添加一个class
。该方法还可以附加内联样式 - 在 CSS 层次结构中了解更多。
[19]:
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()方法接受一个与底层 Styler 的 DataFrame 匹配的 DataFrame。该 DataFrame 将包含作为 css 类的字符串,添加到单个数据单元格中:<table>
的<td>
元素。我们将在工具提示部分添加边框。
[20]:
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)
[20]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
样式函数
处理数据
我们使用以下方法传递您的样式函数。这两种方法都接受一个函数(和一些其他关键字参数)并以某种方式应用于 DataFrame,呈现 CSS 样式。
-
.map()(逐元素):接受一个接受单个值并返回带有 CSS 属性-值对的字符串的函数。
-
.apply()(按列/行/表格方式):接受一个接受 Series 或 DataFrame 并返回具有相同形状的 Series、DataFrame 或 numpy 数组的函数,其中每个元素都是带有 CSS 属性-值对的字符串。此方法根据
axis
关键字参数一次传递您的 DataFrame 的每一列或行或整个表格。对于按列使用axis=0
,按行使用axis=1
,对于一次使用整个表格使用axis=None
。
这种方法非常适用于对数据单元格应用多个复杂逻辑。我们创建一个新的 DataFrame 来演示这一点。
[22]:
np.random.seed(0)
df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
df2.style
[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 |
例如,我们可以构建一个函数,如果文本为负数则着色,并将其与部分淡化微不足道值的单元格的函数链接起来。由于这是逐个元素查看,我们使用map
。
[23]:
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
[23]:
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 中的最大值。在这种情况下,我们使用apply
。下面我们突出显示列中的最大值。
[25]:
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)
[25]:
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 的最大值标记为紫色,行最大值标记为粉色。
[27]:
s2.apply(highlight_max, props='color:white;background-color:pink;', axis=1)\
.apply(highlight_max, props='color:white;background-color:purple', axis=None)
[27]:
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 |
最后一个示例显示了某些样式被其他样式覆盖的情况。通常,最近应用的样式是活动的,但您可以在 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
应用程序可用。
[29]:
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)
[29]:
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。
[30]:
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)
[30]:
多种癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
添加工具提示(自版本 1.3.0 起)可以使用.set_tooltips()方法来完成,方式与您可以通过提供基于字符串的 DataFrame 添加 CSS 类到数据单元格的方式相同。您不必为工具提示指定css_class
名称或任何 cssprops
,因为有标准默认值,但如果您想要更多的视觉控制,可以选择这样做。
[32]:
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;')
[32]:
多种癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
我们表格中唯一剩下的事情是添加突出显示的边框,以吸引观众注意工具提示。我们将像以前一样使用表格样式创建内部 CSS 类。设置类总是覆盖,因此我们需要确保添加先前的类。
[34]:
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)
[34]:
多种癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
使用切片进行更精细的控制
到目前为止,我们展示的Styler.apply
和Styler.map
函数示例尚未展示subset
参数的使用。这是一个很有用的参数,它允许您灵活地应用样式到特定的行或列,而无需将该逻辑编码到您的style
函数中。
传递给subset
的值类似于对 DataFrame 进行切片;
-
将标量视为列标签
-
将列表(或 Series 或 NumPy 数组)视为多列标签
-
元组被视为
(行索引器,列索引器)
考虑使用pd.IndexSlice
构建最后一个元组。我们将创建一个 MultiIndexed DataFrame 来展示功能。
[36]:
df3 = pd.DataFrame(np.random.randn(4,4),
pd.MultiIndex.from_product([['A', 'B'], ['r1', 'r2']]),
columns=['c1','c2','c3','c4'])
df3
[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 |
我们将使用子集来用红色文字突出显示第三和第四列中的最大值。我们将用黄色突出显示切片区域。
[37]:
slice_ = ['c3', '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 | -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
使用,则可以更灵活地跨越两个维度进行索引。
[38]:
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_)
[38]:
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
一起使用时对行进行子选择的灵活性。
[39]:
slice_ = idx[idx[:,'r2'], :]
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 | -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 |
还有提供条件过滤的空间。
假设我们想要突出显示仅在第 2 和第 4 列中的最大值,前提是第 1 和第 3 列的总和小于-2.0 (基本上排除行 (:,'r2')
)。
[40]:
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_)
[40]:
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 |
目前仅支持基于标签的切片,不支持位置的切片,也不支持可调用对象。
如果您的样式函数使用了subset
或axis
关键字参数,请考虑将函数包装在functools.partial
中,部分化该关键字。
my_func2 = functools.partial(my_func, subset=42)
优化
通常,对于较小的表格和大多数情况,渲染的 HTML 不需要优化,我们并不真正推荐这样做。有两种情况值得考虑:
-
如果您正在渲染和设计一个非常大的 HTML 表格,某些浏览器可能会出现性能问题。
-
如果您正在使用
Styler
动态创建在线用户界面的一部分,并希望提高网络性能。
在这里,我们建议采取以下步骤来实施:
1. 移除 UUID 和 cell_ids
忽略 uuid
并将 cell_ids
设置为 False
。这将防止不必要的 HTML。
这是次优的:
[41]:
df4 = pd.DataFrame([[1,2],[3,4]])
s4 = df4.style
这是更好的:
[42]:
from pandas.io.formats.style import Styler
s4 = Styler(df4, uuid_len=0, cell_ids=False)
2. 使用表格样式
使用表格样式是可能的(例如,一次为所有单元格或行或列),因为 CSS 几乎总是比其他格式更有效。
这是次优的:
[43]:
props = 'font-family: "Times New Roman", Times, serif; color: #e83e8c; font-size:1.3em;'
df4.style.map(lambda x: props, subset=[1])
[43]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
这是更好的:
[44]:
df4.style.set_table_styles([{'selector': 'td.col1', 'props': props}])
[44]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
3. 设置类而不是使用 Styler 函数
对于大型数据框,其中许多单元格应用相同的样式,将样式声明为类并将这些类应用于数据单元格可能更有效,而不是直接应用样式于单元格。然而,当您不关心优化时,使用 Styler 函数 api 可能仍然更容易。
这是次优的:
[45]:
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)
[45]:
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 |
这是更好的:
[46]:
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)
[46]:
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 的信息。
[47]:
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" > </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>
[48]:
html
[48]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
内置样式
一些样式函数是如此常见,以至于我们已经“内置”到 Styler
中,因此您不必自己编写并应用它们。当前这些函数的列表如下:
-
.highlight_null:用于识别缺失数据。
-
.highlight_min 和 .highlight_max:用于识别数据中的极值。
-
.highlight_between 和 .highlight_quantile: 用于识别数据中的类别。
-
.background_gradient: 基于数值范围高亮单元格的灵活方法。
-
.text_gradient: 基于数值范围高亮文本的类似方法。
-
.bar: 在单元格背景中显示迷你图表。
每个函数的个别文档通常会提供更多关于它们参数的示例。
高亮空值
[49]:
df2.iloc[0,2] = np.nan
df2.iloc[4,3] = np.nan
df2.loc[:4].style.highlight_null(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 |
高亮最小值或最大值
[50]:
df2.loc[:4].style.highlight_max(axis=1, props='color:white; font-weight:bold; background-color:darkblue;')
[50]:
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 |
高亮区间
该方法接受浮点数范围,或者索引匹配的 NumPy 数组或 Series。
[51]:
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;')
[51]:
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 |
高亮分位数
用于检测最高或最低百分位值
[52]:
df2.loc[:4].style.highlight_quantile(q_left=0.85, axis=None, color='yellow')
[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 |
背景渐变和文本渐变
你可以使用 background_gradient
和 text_gradient
方法创建“热图”。这需要 matplotlib,我们将使用 Seaborn 来获得漂亮的颜色映射。
[53]:
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
df2.style.background_gradient(cmap=cm)
[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 |
[54]:
df2.style.text_gradient(cmap=cm)
[54]:
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 |
.背景渐变 和 .文本渐变 有许多关键字参数可用于自定义渐变和颜色。请参阅文档。
设置属性
当样式实际上不依赖于值时,请使用 Styler.set_properties
。这只是一个简单的 .map
的包装器,其中函数为所有单元格返回相同的属性。
[55]:
df2.loc[:4].style.set_properties(**{'background-color': 'black',
'color': 'lawngreen',
'border-color': 'white'})
[55]:
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 中包含“条形图”。
[56]:
df2.style.bar(subset=['A', 'B'], color='#d65f5f')
[56]:
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
选项来更改上述内容,结���设置 vmin
和 vmax
限制,图形的 width
,以及单元格的底层 css props
,留出空间来显示文本和条形图。我们还使用 text_gradient
来使用 matplotlib 颜色映射将文本着色为与条形图相同的颜色(尽管在这种情况下,可能最好不使用此额外效果)。
[57]:
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)
[57]:
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 |
以下示例旨在突出新对齐选项的行为:
[59]:
HTML(head)
[59]:
对齐 | 全负数 | 正负数混合 | 全正数 | 大正数 |
---|---|---|---|---|
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 |
|
平均 |
---|
| |
| --- |
| -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
导出样式,并使用 df1.style.set
在第二个 DataFrame 上导入它。
[60]:
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
[60]:
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 |
[61]:
style2 = df3.style
style2.use(style1.export())
style2
[61]:
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 使用后被重新评估。
限制
-
仅 DataFrame(使用
Series.to_frame().style
) -
索引和列不需要唯一,但是某些样式函数只能与唯一索引一起使用。
-
没有大型的 repr,构建性能不是很好;尽管我们有一些 HTML 优化
-
你只能应用样式,不能插入新的 HTML 实体,除非通过子类化。
其他有趣且有用的东西
这里有一些有趣的例子。
小部件
Styler
与小部件的交互效果相当不错。如果你在网上查看而不是自己运行笔记本,你将错过交互式调整颜色板的功能。
[62]:
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)
)
放大
[63]:
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')])
]
[64]:
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())
[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 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0.23 | 1.03 | -0.84 | -0.59 | -0.96 | -0.22 | -0.62 | 1.84 | -2.05 | 0.87 | -0.92 | -0.23 | 2.15 | -1.33 | 0.08 | -1.25 | 1.20 | -1.05 | 1.06 | -0.42 | 2.29 | -2.59 | 2.82 | 0.68 | -1.58 |
1 | -1.75 | 1.56 | -1.13 | -1.10 | 1.03 | 0.00 | -2.46 | 3.45 | -1.66 | 1.27 | -0.52 | -0.02 | 1.52 | -1.09 | -1.86 | -1.13 | -0.68 | -0.81 | 0.35 | -0.06 | 1.79 | -2.82 | 2.26 | 0.78 | 0.44 |
2 | -0.65 | 3.22 | -1.76 | 0.52 | 2.20 | -0.37 | -3.00 | 3.73 | -1.87 | 2.46 | 0.21 | -0.24 | -0.10 | -0.78 | -3.02 | -0.82 | -0.21 | -0.23 | 0.86 | -0.68 | 1.45 | -4.89 | 3.03 | 1.91 | 0.61 |
3 | -1.62 | 3.71 | -2.31 | 0.43 | 4.17 | -0.43 | -3.86 | 4.16 | -2.15 | 1.08 | 0.12 | 0.60 | -0.89 | 0.27 | -3.67 | -2.71 | -0.31 | -1.59 | 1.35 | -1.83 | 0.91 | -5.80 | 2.81 | 2.11 | 0.28 |
4 | -3.35 | 4.48 | -1.86 | -1.70 | 5.19 | -1.02 | -3.81 | 4.72 | -0.72 | 1.08 | -0.18 | 0.83 | -0.22 | -1.08 | -4.27 | -2.88 | -0.97 | -1.78 | 1.53 | -1.80 | 2.21 | -6.34 | 3.34 | 2.49 | 2.09 |
5 | -0.84 | 4.23 | -1.65 | -2.00 | 5.34 | -0.99 | -4.13 | 3.94 | -1.06 | -0.94 | 1.24 | 0.09 | -1.78 | -0.11 | -4.45 | -0.85 | -2.06 | -1.35 | 0.80 | -1.63 | 1.54 | -6.51 | 2.80 | 2.14 | 3.77 |
6 | -0.74 | 5.35 | -2.11 | -1.13 | 4.20 | -1.85 | -3.20 | 3.76 | -3.22 | -1.23 | 0.34 | 0.57 | -1.82 | 0.54 | -4.43 | -1.83 | -4.03 | -2.62 | -0.20 | -4.68 | 1.93 | -8.46 | 3.34 | 2.52 | 5.81 |
7 | -0.44 | 4.69 | -2.30 | -0.21 | 5.93 | -2.63 | -1.83 | 5.46 | -4.50 | -3.16 | -1.73 | 0.18 | 0.11 | 0.04 | -5.99 | -0.45 | -6.20 | -3.89 | 0.71 | -3.95 | 0.67 | -7.26 | 2.97 | 3.39 | 6.66 |
8 | 0.92 | 5.80 | -3.33 | -0.65 | 5.99 | -3.19 | -1.83 | 5.63 | -3.53 | -1.30 | -1.61 | 0.82 | -2.45 | -0.40 | -6.06 | -0.52 | -6.60 | -3.48 | -0.04 | -4.60 | 0.51 | -5.85 | 3.23 | 2.40 | 5.08 |
9 | 0.38 | 5.54 | -4.49 | -0.80 | 7.05 | -2.64 | -0.44 | 5.35 | -1.96 | -0.33 | -0.80 | 0.26 | -3.37 | -0.82 | -6.05 | -2.61 | -8.45 | -4.45 | 0.41 | -4.71 | 1.89 | -6.93 | 2.14 | 3.00 | 5.16 |
10 | 2.06 | 5.84 | -3.90 | -0.98 | 7.78 | -2.49 | -0.59 | 5.59 | -2.22 | -0.71 | -0.46 | 1.80 | -2.79 | 0.48 | -5.97 | -3.44 | -7.77 | -5.49 | -0.70 | -4.61 | -0.52 | -7.72 | 1.54 | 5.02 | 5.81 |
11 | 1.86 | 4.47 | -2.17 | -1.38 | 5.90 | -0.49 | 0.02 | 5.78 | -1.04 | -0.60 | 0.49 | 1.96 | -1.47 | 1.88 | -5.92 | -4.55 | -8.15 | -3.42 | -2.24 | -4.33 | -1.17 | -7.90 | 1.36 | 5.31 | 5.83 |
12 | 3.19 | 4.22 | -3.06 | -2.27 | 5.93 | -2.64 | 0.33 | 6.72 | -2.84 | -0.20 | 1.89 | 2.63 | -1.53 | 0.75 | -5.27 | -4.53 | -7.57 | -2.85 | -2.17 | -4.78 | -1.13 | -8.99 | 2.11 | 6.42 | 5.60 |
13 | 2.31 | 4.45 | -3.87 | -2.05 | 6.76 | -3.25 | -2.17 | 7.99 | -2.56 | -0.80 | 0.71 | 2.33 | -0.16 | -0.46 | -5.10 | -3.79 | -7.58 | -4.00 | 0.33 | -3.67 | -1.05 | -8.71 | 2.47 | 5.87 | 6.71 |
14 | 3.78 | 4.33 | -3.88 | -1.58 | 6.22 | -3.23 | -1.46 | 5.57 | -2.93 | -0.33 | -0.97 | 1.72 | 3.61 | 0.29 | -4.21 | -4.10 | -6.68 | -4.50 | -2.19 | -2.43 | -1.64 | -9.36 | 3.36 | 6.11 | 7.53 |
15 | 5.64 | 5.31 | -3.98 | -2.26 | 5.91 | -3.30 | -1.03 | 5.68 | -3.06 | -0.33 | -1.16 | 2.19 | 4.20 | 1.01 | -3.22 | -4.31 | -5.74 | -4.44 | -2.30 | -1.36 | -1.20 | -11.27 | 2.59 | 6.69 | 5.91 |
16 | 4.08 | 4.34 | -2.44 | -3.30 | 6.04 | -2.52 | -0.47 | 5.28 | -4.84 | 1.58 | 0.23 | 0.10 | 5.79 | 1.80 | -3.13 | -3.85 | -5.53 | -2.97 | -2.13 | -1.15 | -0.56 | -13.13 | 2.07 | 6.16 | 4.94 |
17 | 5.64 | 4.57 | -3.53 | -3.76 | 6.58 | -2.58 | -0.75 | 6.58 | -4.78 | 3.63 | -0.29 | 0.56 | 5.76 | 2.05 | -2.27 | -2.31 | -4.95 | -3.16 | -3.06 | -2.43 | 0.84 | -12.57 | 3.56 | 7.36 | 4.70 |
18 | 5.99 | 5.82 | -2.85 | -4.15 | 7.12 | -3.32 | -1.21 | 7.93 | -4.85 | 1.44 | -0.63 | 0.35 | 7.47 | 0.87 | -1.52 | -2.09 | -4.23 | -2.55 | -2.46 | -2.89 | 1.90 | -9.74 | 3.43 | 7.07 | 4.39 |
19 | 4.03 | 6.23 | -4.10 | -4.11 | 7.19 | -4.10 | -1.52 | 6.53 | -5.21 | -0.24 | 0.01 | 1.16 | 6.43 | -1.97 | -2.64 | -1.66 | -5.20 | -3.25 | -2.87 | -1.65 | 1.64 | -10.66 | 2.83 | 7.48 | 3.94 |
粘性标题
如果您在笔记本中显示一个大的矩阵或 DataFrame,但您想要始终看到列和行标题,您可以使用.set_sticky 方法来操作表格样式 CSS。
[65]:
bigdf = pd.DataFrame(np.random.randn(16, 100))
bigdf.style.set_sticky(axis="index")
[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 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | -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 |
| 1 | 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 |
| 2 | 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 |
| 3 | -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 |
| 4 | -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 |
| 5 | -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 |
| 6 | 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 |
| 7 | 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 |
| 8 | -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 |
| 9 | -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 |
| 10 | -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 |
| 11 | -0.625210 | 0.288911 | 0.288374 | -1.372667 | -0.591395 | -0.478942 | 1.335664 | -0.459855 | -1.615975 | -1.189676 | 0.374767 | -2.488733 | 0.586656 | -1.422008 | 0.496030 | 1.911128 | -0.560660 | -0.499614 | -0.372171 | -1.833069 | 0.237124 | -0.944446 | 0.912140 | 0.359790 | -1.359235 | 0.166966 | -0.047107 | -0.279789 | -0.594454 | -0.739013 | -1.527645 | 0.401668 | 1.791252 | -2.774848 | 0.523873 | 2.207585 | 0.488999 | -0.339283 | 0.131711 | 0.018409 | 1.186551 | -0.424318 | 1.554994 | -0.205917 | -0.934975 | 0.654102 | -1.227761 | -0.461025 | -0.421201 | -0.058615 | -0.584563 | 0.336913 | -0.477102 | -1.381463 | 0.757745 | -0.268968 | 0.034870 | 1.231686 | 0.236600 | 1.234720 | -0.040247 | 0.029582 | 1.034905 | 0.380204 | -0.012108 | -0.859511 | -0.990340 | -1.205172 | -1.030178 | 0.426676 | 0.497796 | -0.876808 | 0.957963 | 0.173016 | 0.131612 | -1.003556 | -1.069908 | -1.799207 | 1.429598 | -0.116015 | -1.454980 | 0.261917 | 0.444412 | 0.273290 | 0.844115 | 0.218745 | -1.033350 | -1.188295 | 0.058373 | 0.800523 | -1.627068 | 0.861651 | 0.871018 | -0.003733 | -0.243354 | 0.947296 | 0.509406 | 0.044546 | 0.266896 | 1.337165 |
| 12 | 0.699142 | -1.928033 | 0.105363 | 1.042322 | 0.715206 | -0.763783 | 0.098798 | -1.157898 | 0.134105 | 0.042041 | 0.674826 | 0.165649 | -1.622970 | -3.131274 | 0.597649 | -1.880331 | 0.663980 | -0.256033 | -1.524058 | 0.492799 | 0.221163 | 0.429622 | -0.659584 | 1.264506 | -0.032131 | -2.114907 | -0.264043 | 0.457835 | -0.676837 | -0.629003 | 0.489145 | -0.551686 | 0.942622 | -0.512043 | -0.455893 | 0.021244 | -0.178035 | -2.498073 | -0.171292 | 0.323510 | -0.545163 | -0.668909 | -0.150031 | 0.521620 | -0.428980 | 0.676463 | 0.369081 | -0.724832 | 0.793542 | 1.237422 | 0.401275 | 2.141523 | 0.249012 | 0.486755 | -0.163274 | 0.592222 | -0.292600 | -0.547168 | 0.619104 | -0.013605 | 0.776734 | 0.131424 | 1.189480 | -0.666317 | -0.939036 | 1.105515 | 0.621452 | 1.586605 | -0.760970 | 1.649646 | 0.283199 | 1.275812 | -0.452012 | 0.301361 | -0.976951 | -0.268106 | -0.079255 | -1.258332 | 2.216658 | -1.175988 | -0.863497 | -1.653022 | -0.561514 | 0.450753 | 0.417200 | 0.094676 | -2.231054 | 1.316862 | -0.477441 | 0.646654 | -0.200252 | 1.074354 | -0.058176 | 0.120990 | 0.222522 | -0.179507 | 0.421655 | -0.914341 | -0.234178 | 0.741524 |
| 13 | 0.932714 | 1.423761 | -1.280835 | 0.347882 | -0.863171 | -0.852580 | 1.044933 | 2.094536 | 0.806206 | 0.416201 | -1.109503 | 0.145302 | -0.996871 | 0.325456 | -0.605081 | 1.175326 | 1.645054 | 0.293432 | -2.766822 | 1.032849 | 0.079115 | -1.414132 | 1.463376 | 2.335486 | 0.411951 | -0.048543 | 0.159284 | -0.651554 | -1.093128 | 1.568390 | -0.077807 | -2.390779 | -0.842346 | -0.229675 | -0.999072 | -1.367219 | -0.792042 | -1.878575 | 1.451452 | 1.266250 | -0.734315 | 0.266152 | 0.735523 | -0.430860 | 0.229864 | 0.850083 | -2.241241 | 1.063850 | 0.289409 | -0.354360 | 0.113063 | -0.173006 | 1.386998 | 1.886236 | 0.587119 | -0.961133 | 0.399295 | 1.461560 | 0.310823 | 0.280220 | -0.879103 | -1.326348 | 0.003337 | -1.085908 | -0.436723 | 2.111926 | 0.106068 | 0.615597 | 2.152996 | -0.196155 | 0.025747 | -0.039061 | 0.656823 | -0.347105 | 2.513979 | 1.758070 | 1.288473 | -0.739185 | -0.691592 | -0.098728 | -0.276386 | 0.489981 | 0.516278 | -0.838258 | 0.596673 | -0.331053 | 0.521174 | -0.145023 | 0.836693 | -1.092166 | 0.361733 | -1.169981 | 0.046731 | 0.655377 | -0.756852 | 1.285805 | -0.095019 | 0.360253 | 1.370621 | 0.083010 |
| 14 | 0.888893 | 2.288725 | -1.032332 | 0.212273 | -1.091826 | 1.692498 | 1.025367 | 0.550854 | 0.679430 | -1.335712 | -0.798341 | 2.265351 | -1.006938 | 2.059761 | 0.420266 | -1.189657 | 0.506674 | 0.260847 | -0.533145 | 0.727267 | 1.412276 | 1.482106 | -0.996258 | 0.588641 | -0.412642 | -0.920733 | -0.874691 | 0.839002 | 0.501668 | -0.342493 | -0.533806 | -2.146352 | -0.597339 | 0.115726 | 0.850683 | -0.752239 | 0.377263 | -0.561982 | 0.262783 | -0.356676 | -0.367462 | 0.753611 | -1.267414 | -1.330698 | -0.536453 | 0.840938 | -0.763108 | -0.268100 | -0.677424 | 1.606831 | 0.151732 | -2.085701 | 1.219296 | 0.400863 | 0.591165 | -1.485213 | 1.501979 | 1.196569 | -0.214154 | 0.339554 | -0.034446 | 1.176452 | 0.546340 | -1.255630 | -1.309210 | -0.445437 | 0.189437 | -0.737463 | 0.843767 | -0.605632 | -0.060777 | 0.409310 | 1.285569 | -0.622638 | 1.018193 | 0.880680 | 0.046805 | -1.818058 | -0.809829 | 0.875224 | 0.409569 | -0.116621 | -1.238919 | 3.305724 | -0.024121 | -1.756500 | 1.328958 | 0.507593 | -0.866554 | -2.240848 | -0.661376 | -0.671824 | 0.215720 | -0.296326 | 0.481402 | 0.829645 | -0.721025 | 1.263914 | 0.549047 | -1.234945 |
| 15 | -1.978838 | 0.721823 | -0.559067 | -1.235243 | 0.420716 | -0.598845 | 0.359576 | -0.619366 | -1.757772 | -1.156251 | 0.705212 | 0.875071 | -1.020376 | 0.394760 | -0.147970 | 0.230249 | 1.355203 | 1.794488 | 2.678058 | -0.153565 | -0.460959 | -0.098108 | -1.407930 | -2.487702 | 1.823014 | 0.099873 | -0.517603 | -0.509311 | -1.833175 | -0.900906 | 0.459493 | -0.655440 | 1.466122 | -1.531389 | -0.422106 | 0.421422 | 0.578615 | 0.259795 | 0.018941 | -0.168726 | 1.611107 | -1.586550 | -1.384941 | 0.858377 | 1.033242 | 1.701343 | 1.748344 | -0.371182 | -0.843575 | 2.089641 | -0.345430 | -1.740556 | 0.141915 | -2.197138 | 0.689569 | -0.150025 | 0.287456 | 0.654016 | -1.521919 | -0.918008 | -0.587528 | 0.230636 | 0.262637 | 0.615674 | 0.600044 | -0.494699 | -0.743089 | 0.220026 | -0.242207 | 0.528216 | -0.328174 | -1.536517 | -1.476640 | -1.162114 | -1.260222 | 1.106252 | -1.467408 | -0.349341 | -1.841217 | 0.031296 | -0.076475 | -0.353383 | 0.807545 | 0.779064 | -2.398417 | -0.267828 | 1.549734 | 0.814397 | 0.284770 | -0.659369 | 0.761040 | -0.722067 | 0.810332 | 1.501295 | 1.440865 | -1.367459 | -0.700301 | -1.540662 | 0.159837 | -0.625415 |
也可以将 MultiIndexes 粘在一起,甚至只针对特定级别进行操作。
[66]:
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])
[66]:
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.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 |
1 | 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 | ||
2 | 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 | ||
3 | -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 | -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 | |
1 | -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 | ||
2 | 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 | ||
3 | 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 | ||
B | 0 | 0 | -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 |
1 | -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 | ||
2 | -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 | ||
3 | -0.625210 | 0.288911 | 0.288374 | -1.372667 | -0.591395 | -0.478942 | 1.335664 | -0.459855 | -1.615975 | -1.189676 | 0.374767 | -2.488733 | 0.586656 | -1.422008 | 0.496030 | 1.911128 | -0.560660 | -0.499614 | -0.372171 | -1.833069 | 0.237124 | -0.944446 | 0.912140 | 0.359790 | -1.359235 | 0.166966 | -0.047107 | -0.279789 | -0.594454 | -0.739013 | -1.527645 | 0.401668 | 1.791252 | -2.774848 | 0.523873 | 2.207585 | 0.488999 | -0.339283 | 0.131711 | 0.018409 | 1.186551 | -0.424318 | 1.554994 | -0.205917 | -0.934975 | 0.654102 | -1.227761 | -0.461025 | -0.421201 | -0.058615 | -0.584563 | 0.336913 | -0.477102 | -1.381463 | 0.757745 | -0.268968 | 0.034870 | 1.231686 | 0.236600 | 1.234720 | -0.040247 | 0.029582 | 1.034905 | 0.380204 | -0.012108 | -0.859511 | -0.990340 | -1.205172 | -1.030178 | 0.426676 | 0.497796 | -0.876808 | 0.957963 | 0.173016 | 0.131612 | -1.003556 | -1.069908 | -1.799207 | 1.429598 | -0.116015 | -1.454980 | 0.261917 | 0.444412 | 0.273290 | 0.844115 | 0.218745 | -1.033350 | -1.188295 | 0.058373 | 0.800523 | -1.627068 | 0.861651 | 0.871018 | -0.003733 | -0.243354 | 0.947296 | 0.509406 | 0.044546 | 0.266896 | 1.337165 | ||
1 | 0 | 0.699142 | -1.928033 | 0.105363 | 1.042322 | 0.715206 | -0.763783 | 0.098798 | -1.157898 | 0.134105 | 0.042041 | 0.674826 | 0.165649 | -1.622970 | -3.131274 | 0.597649 | -1.880331 | 0.663980 | -0.256033 | -1.524058 | 0.492799 | 0.221163 | 0.429622 | -0.659584 | 1.264506 | -0.032131 | -2.114907 | -0.264043 | 0.457835 | -0.676837 | -0.629003 | 0.489145 | -0.551686 | 0.942622 | -0.512043 | -0.455893 | 0.021244 | -0.178035 | -2.498073 | -0.171292 | 0.323510 | -0.545163 | -0.668909 | -0.150031 | 0.521620 | -0.428980 | 0.676463 | 0.369081 | -0.724832 | 0.793542 | 1.237422 | 0.401275 | 2.141523 | 0.249012 | 0.486755 | -0.163274 | 0.592222 | -0.292600 | -0.547168 | 0.619104 | -0.013605 | 0.776734 | 0.131424 | 1.189480 | -0.666317 | -0.939036 | 1.105515 | 0.621452 | 1.586605 | -0.760970 | 1.649646 | 0.283199 | 1.275812 | -0.452012 | 0.301361 | -0.976951 | -0.268106 | -0.079255 | -1.258332 | 2.216658 | -1.175988 | -0.863497 | -1.653022 | -0.561514 | 0.450753 | 0.417200 | 0.094676 | -2.231054 | 1.316862 | -0.477441 | 0.646654 | -0.200252 | 1.074354 | -0.058176 | 0.120990 | 0.222522 | -0.179507 | 0.421655 | -0.914341 | -0.234178 | 0.741524 | |
1 | 0.932714 | 1.423761 | -1.280835 | 0.347882 | -0.863171 | -0.852580 | 1.044933 | 2.094536 | 0.806206 | 0.416201 | -1.109503 | 0.145302 | -0.996871 | 0.325456 | -0.605081 | 1.175326 | 1.645054 | 0.293432 | -2.766822 | 1.032849 | 0.079115 | -1.414132 | 1.463376 | 2.335486 | 0.411951 | -0.048543 | 0.159284 | -0.651554 | -1.093128 | 1.568390 | -0.077807 | -2.390779 | -0.842346 | -0.229675 | -0.999072 | -1.367219 | -0.792042 | -1.878575 | 1.451452 | 1.266250 | -0.734315 | 0.266152 | 0.735523 | -0.430860 | 0.229864 | 0.850083 | -2.241241 | 1.063850 | 0.289409 | -0.354360 | 0.113063 | -0.173006 | 1.386998 | 1.886236 | 0.587119 | -0.961133 | 0.399295 | 1.461560 | 0.310823 | 0.280220 | -0.879103 | -1.326348 | 0.003337 | -1.085908 | -0.436723 | 2.111926 | 0.106068 | 0.615597 | 2.152996 | -0.196155 | 0.025747 | -0.039061 | 0.656823 | -0.347105 | 2.513979 | 1.758070 | 1.288473 | -0.739185 | -0.691592 | -0.098728 | -0.276386 | 0.489981 | 0.516278 | -0.838258 | 0.596673 | -0.331053 | 0.521174 | -0.145023 | 0.836693 | -1.092166 | 0.361733 | -1.169981 | 0.046731 | 0.655377 | -0.756852 | 1.285805 | -0.095019 | 0.360253 | 1.370621 | 0.083010 | ||
2 | 0.888893 | 2.288725 | -1.032332 | 0.212273 | -1.091826 | 1.692498 | 1.025367 | 0.550854 | 0.679430 | -1.335712 | -0.798341 | 2.265351 | -1.006938 | 2.059761 | 0.420266 | -1.189657 | 0.506674 | 0.260847 | -0.533145 | 0.727267 | 1.412276 | 1.482106 | -0.996258 | 0.588641 | -0.412642 | -0.920733 | -0.874691 | 0.839002 | 0.501668 | -0.342493 | -0.533806 | -2.146352 | -0.597339 | 0.115726 | 0.850683 | -0.752239 | 0.377263 | -0.561982 | 0.262783 | -0.356676 | -0.367462 | 0.753611 | -1.267414 | -1.330698 | -0.536453 | 0.840938 | -0.763108 | -0.268100 | -0.677424 | 1.606831 | 0.151732 | -2.085701 | 1.219296 | 0.400863 | 0.591165 | -1.485213 | 1.501979 | 1.196569 | -0.214154 | 0.339554 | -0.034446 | 1.176452 | 0.546340 | -1.255630 | -1.309210 | -0.445437 | 0.189437 | -0.737463 | 0.843767 | -0.605632 | -0.060777 | 0.409310 | 1.285569 | -0.622638 | 1.018193 | 0.880680 | 0.046805 | -1.818058 | -0.809829 | 0.875224 | 0.409569 | -0.116621 | -1.238919 | 3.305724 | -0.024121 | -1.756500 | 1.328958 | 0.507593 | -0.866554 | -2.240848 | -0.661376 | -0.671824 | 0.215720 | -0.296326 | 0.481402 | 0.829645 | -0.721025 | 1.263914 | 0.549047 | -1.234945 | ||
3 | -1.978838 | 0.721823 | -0.559067 | -1.235243 | 0.420716 | -0.598845 | 0.359576 | -0.619366 | -1.757772 | -1.156251 | 0.705212 | 0.875071 | -1.020376 | 0.394760 | -0.147970 | 0.230249 | 1.355203 | 1.794488 | 2.678058 | -0.153565 | -0.460959 | -0.098108 | -1.407930 | -2.487702 | 1.823014 | 0.099873 | -0.517603 | -0.509311 | -1.833175 | -0.900906 | 0.459493 | -0.655440 | 1.466122 | -1.531389 | -0.422106 | 0.421422 | 0.578615 | 0.259795 | 0.018941 | -0.168726 | 1.611107 | -1.586550 | -1.384941 | 0.858377 | 1.033242 | 1.701343 | 1.748344 | -0.371182 | -0.843575 | 2.089641 | -0.345430 | -1.740556 | 0.141915 | -2.197138 | 0.689569 | -0.150025 | 0.287456 | 0.654016 | -1.521919 | -0.918008 | -0.587528 | 0.230636 | 0.262637 | 0.615674 | 0.600044 | -0.494699 | -0.743089 | 0.220026 | -0.242207 | 0.528216 | -0.328174 | -1.536517 | -1.476640 | -1.162114 | -1.260222 | 1.106252 | -1.467408 | -0.349341 | -1.841217 | 0.031296 | -0.076475 | -0.353383 | 0.807545 | 0.779064 | -2.398417 | -0.267828 | 1.549734 | 0.814397 | 0.284770 | -0.659369 | 0.761040 | -0.722067 | 0.810332 | 1.501295 | 1.440865 | -1.367459 | -0.700301 | -1.540662 | 0.159837 | -0.625415 |
HTML 转义
假设您必须在 HTML 中显示 HTML,当渲染器无法区分时可能会有些麻烦。 您可以使用escape
格式选项来处理此问题,甚至可以在包含 HTML 本身的格式化程序中使用它。
[67]:
df4 = pd.DataFrame([['<div></div>', '"&other"', '<span></span>']])
df4.style
[67]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
[68]:
df4.style.format(escape="html")
[68]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
[69]:
df4.style.format('<a href="https://pandas.pydata.org" target="_blank">{}</a>', escape="html")
[69]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
导出到 Excel
从版本 0.20.0 开始,可以使用OpenPyXL
或XlsxWriter
引擎将带有样式的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-style
和border-left-style
),以及所有边的border
简写(border: 1px solid green
)或指定边(border-left: 1px solid green
)。使用border
简写将覆盖之前设置的任何��框属性(有关更多详细信息,请参阅CSS Working Group) -
目前仅支持 CSS2 命名颜色和形式为
#rgb
或#rrggbb
的十六进制颜色。 -
以下伪 CSS 属性也可用于设置 Excel 特定的样式属性:
-
number-format
-
border-style
(用于 Excel 特定样式:“hair”、“mediumDashDot”、“dashDotDot”、“mediumDashDotDot”、“dashDot”、“slantDashDot”或“mediumDashed”)
-
表级样式和数据单元格 CSS 类不包括在导出到 Excel 中:单个单元格必须通过Styler.apply
和/或Styler.map
方法映射其属性。
[70]:
df2.style.\
map(style_negative, props='color:red;').\
highlight_max(axis=0).\
to_excel('styled.xlsx', engine='openpyxl')
输出的屏幕截图:
导出到 LaTeX
从版本 1.3.0 开始,支持将Styler
导出到 LaTeX。.to_latex 方法的文档提供了更多详细信息和大量示例。
更多关于 CSS 和 HTML
层叠样式表(CSS)语言旨在影响浏览器如何呈现 HTML 元素,具有其自己的特点。它从不报告错误:它只是悄悄地忽略它们,不按照您的意图呈现您的对象,因此有时可能令人沮丧。以下是关于Styler
如何创建 HTML 并与 CSS 交互的简要入门,以及避免常见陷阱的建议。
CSS 类和 Id
每个单元格附加的 CSS class
的精确结构如下。
-
具有索引和列名称的单元格包括
index_name
和level<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_trim
或row_trim
id
的结构是T_uuid_level<k>_row<m>_col<n>
,其中level<k>
仅用于标题,标题只会有row<m>
或col<n>
中的一个,取决于需要哪个。默认情况下,我们还为每个 DataFrame 的每个行/列标识符添加了一个唯一的 UUID,以便一个 DataFrame 的样式不会与同一笔记本或页面中的另一个 DataFrame 的样式发生冲突。您可以在优化中阅读更多关于 UUID 使用的内容。
通过调用.to_html()方法,我们可以看到 HTML 的示例。
[71]:
print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.to_html())
<style type="text/css">
</style>
<table id="T_a1de3">
<thead>
<tr>
<th class="blank level0" > </th>
<th id="T_a1de3_level0_col0" class="col_heading level0 col0" >c1</th>
<th id="T_a1de3_level0_col1" class="col_heading level0 col1" >c2</th>
</tr>
</thead>
<tbody>
<tr>
<th id="T_a1de3_level0_row0" class="row_heading level0 row0" >i1</th>
<td id="T_a1de3_row0_col0" class="data row0 col0" >1</td>
<td id="T_a1de3_row0_col1" class="data row0 col1" >2</td>
</tr>
<tr>
<th id="T_a1de3_level0_row1" class="row_heading level0 row1" >i2</th>
<td id="T_a1de3_row1_col0" class="data row1 col0" >3</td>
<td id="T_a1de3_row1_col1" class="data row1 col1" >4</td>
</tr>
</tbody>
</table>
CSS 层次结构
示例表明,当 CSS 样式重叠时,HTML 渲染中排在后面的样式优先。因此,以下会产生不同的结果:
[72]:
df4 = pd.DataFrame([['text']])
df4.style.map(lambda x: 'color:green;')\
.map(lambda x: 'color:red;')
[72]:
0 | |
---|---|
0 | 文本 |
[73]:
df4.style.map(lambda x: 'color:red;')\
.map(lambda x: 'color:green;')
[73]:
0 | |
---|---|
0 | 文本 |
这仅适用于层次结构或重要性相等的 CSS 规则。您可以在这里阅读更多关于 CSS 特异性的内容,但对于我们的目的,总结关键点就足够了:
每个 HTML 元素的 CSS 重要性分数是通过从零开始并添加以下内容得出的:
-
1000 用于内联样式属性
-
100 用于每个 ID
-
10 用于每个属性、类或伪类
-
1 用于每个元素名称或伪元素
让我们用这个来描述以下配置的操作
[74]:
df4.style.set_uuid('a_')\
.set_table_styles([{'selector': 'td', 'props': 'color:red;'}])\
.map(lambda x: 'color:green;')
[74]:
0 | |
---|---|
0 | 文本 |
这段文字是红色的,因为生成的选择器#T_a_ td
价值为 101(ID 加元素),而#T_a_row0_col0
只值为 100(ID),因此尽管在 HTML 中排在前面,但被认为是次要的。
[75]:
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']]))
[75]:
0 | |
---|---|
0 | 文本 |
在上述情况下,文本是蓝色的,因为选择器#T_b_ .cls-1
价值为 110(ID 加类),优先级更高。
[76]:
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']]))
[76]:
0 | |
---|---|
0 | 文本 |
现在我们创建了另一个表格样式,这次选择器T_c_ td.data
(ID 加元素加类)被提升到 111。
如果您的样式未能应用,并且真的很令人沮丧,请尝试使用!important
王牌。
[77]:
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']]))
[77]:
0 | |
---|---|
0 | 文本 |
终于得到了那个绿色的文本!
可扩展性
pandas 的核心是,并将始终是其“高性能、易于使用的数据结构”。考虑到这一点,我们希望DataFrame.style
实现两个目标
-
提供一个对交互使用愉悦且对许多任务“足够好”的 API
-
为专用库提供基础
如果您在此基础上构建了一个很棒的库,请告诉我们,我们将链接到它。
子类化
如果默认模板不完全符合您的需求,您可以创建 Styler 的子类并扩展或覆盖模板。我们将展示一个扩展默认模板以在每个表格之前插入自定义标题的示例。
[78]:
from jinja2 import Environment, ChoiceLoader, FileSystemLoader
from IPython.display import HTML
from pandas.io.formats.style import Styler
我们将使用以下模板:
[79]:
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
的子类,让它知道这个模板。
[80]:
class MyStyler(Styler):
env = Environment(
loader=ChoiceLoader([
FileSystemLoader("templates"), # contains ours
Styler.loader, # the default
])
)
template_html_table = env.get_template("myhtml.tpl")
注意我们在环境的加载器中包含了原始加载器。这是因为我们扩展了原始模板,所以 Jinja 环境需要能够找到它。
现在我们可以使用自定义样式。它的__init__
接受一个 DataFrame。
[81]:
MyStyler(df3)
[81]:
我的表
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
方法中提供值。
[82]:
HTML(MyStyler(df3).to_html(table_title="Extending Example"))
[82]:
扩展示例
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
方法,它与自定义子类相同。
[83]:
EasyStyler = Styler.from_custom_template("templates", "myhtml.tpl")
HTML(EasyStyler(df3).to_html(table_title="Another Title"))
[83]:
另一个标题
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 |
模板结构
这是样式生成模板和表生成模板的模板结构:
样式模板:
[85]:
HTML(style_structure)
[85]:
before_stylestyle
<style type="text/css">
table_stylesbefore_cellstylecellstyle
</style>
表模板:
[87]:
HTML(table_structure)
[87]:
before_tabletable
<table ...>
captiontheadbefore_head_rowshead_tr(循环遍历标题)after_head_rowstbodybefore_rowstr(循环遍历数据行)after_rows
</table>
after_table
查看 GitHub 仓库 中的模板以获取更多详细信息。
Styler 对象和自定义显示
样式和输出显示自定义应在处理 DataFrame 中的数据之后执行。如果对 DataFrame 进行进一步更改,Styler 不会动态更新。DataFrame.style
属性是一个返回 Styler 对象的属性。它在 Jupyter Notebook 中自动呈现,具有定义的 _repr_html_
方法。
Styler 可用于大数据,但主要设计用于小数据,目前可以输出以下格式:
-
HTML
-
LaTeX
-
字符串(以及 CSV 扩展)
-
Excel
-
(JSON 目前不可用)
这三个都有显示自定义方法,旨在格式化和自定义输出。这些包括:
-
格式化值,索引和列标题,使用 .format() 和 .format_index(),
-
重命名索引或列标题标签,使用.relabel_index()
-
隐藏某些列、索引和/或列标题,或索引名称,使用.hide()
-
连接相似的数据框,使用.concat()
格式化显示
格式化值
Styler 区分显示值和实际值,无论是数据值还是索引或列标题。要控制显示值,文本以字符串形式打印在每个单元格中,我们可以使用.format()和.format_index()方法根据格式规范字符串或接受单个值并返回字符串的可调用对象来操作。可以为整个表格、索引、单独的列或 MultiIndex 级别定义此功能。我们还可以覆盖索引名称。
此外,格式函数具有精度参数,专门用于格式化浮点数,以及小数和千位分隔符来支持其他语言环境,一个na_rep参数用于显示缺失数据,以及一个escape和hyperlinks参数用于帮助显示安全的 HTML 或安全的 LaTeX。默认格式化程序配置为采用 pandas 的全局选项,如styler.format.precision
选项,可使用with pd.option_context('format.precision', 2):
进行控制。
[2]:
import pandas as pd
import numpy as np
import matplotlib as mpl
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)
[2]:
字符串 | 整数 | 浮点数 | |
---|---|---|---|
第一行 | 亚当 | 1 | 1,123 |
第二行 | 迈克 | 3 | 1.000,230 |
使用 Styler 来操纵显示是一个有用的功能,因为保持索引和数据值用于其他目的可以更好地控制。您不必覆盖 DataFrame 以按照您喜欢的方式显示它。以下是一个更全面的示例,展示了在仍依赖底层数据进行索引和计算的情况下使用格式化函数。
[3]:
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
[3]:
东京 | 北京 | |
---|---|---|
2021-01-01 | 2.552517 | 1.976602 |
2021-01-02 | 1.665753 | 3.757927 |
2021-01-03 | 4.679882 | 2.242228 |
2021-01-04 | 1.268592 | 0.915911 |
2021-01-05 | 0.258386 | 4.647607 |
2021-01-06 | 1.279295 | 4.642458 |
2021-01-07 | 0.560487 | 3.670073 |
2021-01-08 | 0.980423 | 1.026641 |
2021-01-09 | 1.471664 | 1.384219 |
2021-01-10 | 4.617766 | 4.251794 |
[4]:
weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
[4]:
天气状况
东京 | 北京 | |
---|---|---|
星期一 | 干燥 | 干燥 |
星期二 | 干燥 | 大雨 |
星期三 | 干燥 | 大雨 |
星期四 | 干燥 | 大雨 |
星期五 | 干燥 | 干燥 |
隐藏数据
索引和列标题可以完全隐藏,也可以选择要排除的行或列。这两个选项都使用相同的方法执行。
可以通过调用.hide()而不带任何参数来隐藏索引的渲染,如果您的索引是基于整数的,这可能很有用。类似地,可以通过调用.hide(axis=”columns”)而不带任何其他参数来隐藏列标题。
可以通过调用相同的.hide()方法并将行/列标签、类似列表或行/列标签的切片传递给subset
参数来隐藏渲染中的特定行或列。
隐藏不会改变 CSS 类的整数排列,例如,隐藏数据框的前两列意味着列类索引仍将从col2
开始,因为col0
和col1
将被简单忽略。
[5]:
df = pd.DataFrame(np.random.randn(5, 5))
df.style \
.hide(subset=[0, 2, 4], axis=0) \
.hide(subset=[0, 2, 4], axis=1)
[5]:
1 | 3 | |
---|---|---|
1 | 0.561440 | -0.858225 |
3 | 0.176255 | 0.876609 |
要将功能反转为显示功能,最佳做法是组成一个隐藏项目列表。
[6]:
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)
[6]:
0 | 2 | 4 | |
---|---|---|---|
0 | -0.056334 | -1.188982 | 0.482870 |
2 | -0.718731 | -0.499113 | -1.350023 |
4 | -0.720169 | 1.225336 | -0.512159 |
连接数据框输出
两个或更多的样式化对象可以连接在一起,前提是它们共享相同的列。这对于显示数据框的摘要统计信息非常有用,并经常与 DataFrame.agg 结合使用。
由于连接的对象是样式化的,它们可以独立进行样式设置,如下所示,它们的连接保留了这些样式。
[7]:
summary_styler = df.agg(["sum", "mean"]).style \
.format(precision=3) \
.relabel_index(["Sum", "Average"])
df.style.format(precision=1).concat(summary_styler)
[7]:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | -0.1 | 0.8 | -1.2 | 0.3 | 0.5 |
1 | 0.5 | 0.6 | 0.1 | -0.9 | 0.9 |
2 | -0.7 | -0.8 | -0.5 | 0.2 | -1.4 |
3 | 2.2 | 0.2 | 0.9 | 0.9 | 0.1 |
4 | -0.7 | -1.0 | 1.2 | -0.5 | -0.5 |
总和 | 1.179 | -0.213 | 0.506 | -0.082 | -0.430 |
平均值 | 0.236 | -0.043 | 0.101 | -0.016 | -0.086 |
格式化数值
Styler 区分显示值和实际值,无论是数据值还是索引或列标题。要控制显示值,文本将作为字符串打印在每个单元格中,我们可以使用.format()和.format_index()方法根据格式规范字符串或一个接受单个值并返回一个字符串的可调用对象来操作这一点。可以为整个表格、索引或单独的列或多级索引级别定义这一点。我们还可以覆盖索引名称。
此外,格式函数具有精度参数,专门用于格式化浮点数,以及小数和千位分隔符以支持其他语言环境,一个na_rep参数用于显示缺失数据,以及一个escape和hyperlinks参数用于帮助显示安全的 HTML 或安全的 LaTeX。默认格式化程序配置为采用 pandas 的全局选项,如styler.format.precision
选项,可使用with pd.option_context('format.precision', 2):
进行控制。
[2]:
import pandas as pd
import numpy as np
import matplotlib as mpl
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)
[2]:
STRINGS | INTS | FLOATS | |
---|---|---|---|
row 1 | Adam | 1 | 1,123 |
row 2 | Mike | 3 | 1.000,230 |
使用 Styler 来操纵显示是一个有用的功能,因为保留索引和数据值以供其他目的使用可以更好地控制。您不必覆盖 DataFrame 以按照您喜欢的方式显示它。以下是一个更全面的示例,展示了在仍依赖底层数据进行索引和计算的情况下使用格式化函数的更多示例。
[3]:
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
[3]:
Tokyo | Beijing | |
---|---|---|
2021-01-01 | 2.552517 | 1.976602 |
2021-01-02 | 1.665753 | 3.757927 |
2021-01-03 | 4.679882 | 2.242228 |
2021-01-04 | 1.268592 | 0.915911 |
2021-01-05 | 0.258386 | 4.647607 |
2021-01-06 | 1.279295 | 4.642458 |
2021-01-07 | 0.560487 | 3.670073 |
2021-01-08 | 0.980423 | 1.026641 |
2021-01-09 | 1.471664 | 1.384219 |
2021-01-10 | 4.617766 | 4.251794 |
[4]:
weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
[4]:
天气状况
Tokyo | Beijing | |
---|---|---|
Monday | Dry | Dry |
Tuesday | Dry | Heavy Rain |
Wednesday | Dry | Heavy Rain |
Thursday | Dry | Heavy Rain |
Friday | Dry | Dry |
隐藏数据
索引和列标题可以完全隐藏,也可以选择要排除的行或列。这两个选项使用相同的方法执行。
可以通过调用.hide()而不带任何参数来隐藏索引的呈现,如果您的索引是基于整数的,这可能很有用。同样,通过调用.hide(axis=”columns”)而不带任何其他参数来隐藏列标题。
可以通过调用相同的.hide()方法并传递行/列标签、类似列表或行/列标签的切片来隐藏特定行或列以进行呈现。
隐藏不会改变 CSS 类的整数排列,例如,隐藏 DataFrame 的前两列意味着列类索引仍将从col2
开始,因为col0
和col1
将被简单忽略。
[5]:
df = pd.DataFrame(np.random.randn(5, 5))
df.style \
.hide(subset=[0, 2, 4], axis=0) \
.hide(subset=[0, 2, 4], axis=1)
[5]:
1 | 3 | |
---|---|---|
1 | 0.561440 | -0.858225 |
3 | 0.176255 | 0.876609 |
要将功能反转为显示功能,最佳实践是组成一个隐藏项目列表。
[6]:
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)
[6]:
0 | 2 | 4 | |
---|---|---|---|
0 | -0.056334 | -1.188982 | 0.482870 |
2 | -0.718731 | -0.499113 | -1.350023 |
4 | -0.720169 | 1.225336 | -0.512159 |
连接 DataFrame 输出
两个或更多的 Stylers 可以连接在一起,前提是它们共享相同的列。这对于显示 DataFrame 的摘要统计信息非常有用,并经常与 DataFrame.agg 结合使用。
由于连接的对象是 Stylers,它们可以独立进行样式设置,如下所示,它们的连接保留了这些样式。
[7]:
summary_styler = df.agg(["sum", "mean"]).style \
.format(precision=3) \
.relabel_index(["Sum", "Average"])
df.style.format(precision=1).concat(summary_styler)
[7]:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | -0.1 | 0.8 | -1.2 | 0.3 | 0.5 |
1 | 0.5 | 0.6 | 0.1 | -0.9 | 0.9 |
2 | -0.7 | -0.8 | -0.5 | 0.2 | -1.4 |
3 | 2.2 | 0.2 | 0.9 | 0.9 | 0.1 |
4 | -0.7 | -1.0 | 1.2 | -0.5 | -0.5 |
总和 | 1.179 | -0.213 | 0.506 | -0.082 | -0.430 |
平均值 | 0.236 | -0.043 | 0.101 | -0.016 | -0.086 |
Styler 对象和 HTML
Styler 最初是为了支持各种 HTML 格式选项而构建的。其 HTML 输出创建了一个 HTML <table>
,并利用 CSS 样式语言来操纵许多参数,包括颜色、字体、边框、背景等。查看这里以获取有关样式化 HTML 表格的更多信息。这使得在开箱即用的情况下具有很大的灵活性,甚至使 Web 开发人员能够将 DataFrame 集成到其现有用户界面设计中。
下面我们展示了默认输出,看起来非常类似于标准的 DataFrame HTML 表示。但是这里的 HTML 已经为每个单元格附加了一些 CSS 类,即使我们还没有创建任何样式。我们可以通过调用.to_html()方法来查看这些,该方法返回原始 HTML 字符串,这对于进一步处理或添加到文件中非常有用 - 请继续阅读有关 CSS 和 HTML 的更多信息。本节还将提供如何将此默认输出转换为更具沟通性的 DataFrame 输出的演示。例如,我们如何构建 s
:
[8]:
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
[8]:
模型: | 决策树 | 回归 | 随机 |
---|---|---|---|
预测值: | 肿瘤 | 非肿瘤 | 肿瘤 |
--- | --- | --- | --- |
实际标签: | |||
--- | --- | --- | --- |
肿瘤 (阳性) | 38.000000 | 2.000000 | 18.000000 |
非肿瘤 (阴性) | 19.000000 | 439.000000 | 6.000000 |
[10]:
s
[10]:
多个癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测值: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤 (阳性) | 38 | 2 |
非肿瘤 (阴性) | 19 | 439 |
我们采取的第一步是从 DataFrame 创建 Styler 对象,然后通过.hide()隐藏不需要的列来选择感兴趣的范围。
[11]:
s = df.style.format('{:.0f}').hide([('Random', 'Tumour'), ('Random', 'Non-Tumour')], axis="columns")
s
[11]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
添加样式的方法
有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 字符串,例如:
[13]:
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])
[13]:
模型: | 决策树 | 回归 |
---|---|---|
预测值: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
接下来,我们只需添加几个针对表格特定部分的样式化元素。在这里要小心,因为我们正在链接方法,我们需要明确指示方法不要覆盖
现有样式。
[15]:
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)
[15]:
模型: | 决策树 | 回归 |
---|---|---|
预测值: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
作为一个便利方法(自版本 1.2.0 起),我们还可以向.set_table_styles()传递一个字典,其中包含行或列键。在幕后,Styler 只是索引这些键,并根据需要向给定的 CSS 选择器添加相关的.col<m>
或.row<n>
类。
[17]:
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)
[17]:
模型: | 决策树 | 回归 |
---|---|---|
预测值: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
设置类和链接到外部 CSS
如果您设计过网站,那么您很可能已经有一个控制其中表格和单元格对象样式的外部 CSS 文件。您可能希望使用这些原生文件,而不是在 Python 中重复所有 CSS(以及重复任何维护工作)。
表属性
通过.set_table_attributes()很容易向主<table>
添加一个class
。这个方法还可以附加内联样式 - 在 CSS 层次结构中了解更多。
[19]:
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()方法接受一个与底层 Styler 的 DataFrame 匹配的 DataFrame。该 DataFrame 将包含作为 css 类添加到单个数据单元格的<td>
元素的字符串:<table>
。我们将内部创建我们的类,将它们添加到表格样式中。我们将在工具提示部分保存添加边框。
[20]:
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)
[20]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
表格属性
使用 .set_table_attributes() 非常容易向主 <table>
添加一个 class
。此方法还可以附加内联样式 - 请在 CSS 层次结构 中阅读更多。
[19]:
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() 方法接受一个与底层 Styler 的 DataFrame 具有匹配索引和列的 DataFrame。该 DataFrame 将包含字符串作为要添加到单个数据单元的 css 类的类:<table>
的 <td>
元素。我们将不使用外部 CSS,而是在内部创建我们的类并将它们添加到表格样式中。我们将保存添加边框的工作,直到 工具提示部分。
[20]:
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)
[20]:
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
Styler 函数
数据处理
我们使用以下方法来传递您的样式函数。这两种方法都接受一个函数(以及一些其他关键字参数),并以某种方式将其应用于 DataFrame,从而呈现 CSS 样式。
-
.map()(逐元素):接受一个函数,该函数接受一个值,并返回一个带有 CSS 属性-值对的字符串。
-
.apply()(列 / 行 / 表格):接受一个函数,该函数接受一个 Series 或 DataFrame,并返回一个形状相同的 Series、DataFrame 或 numpy 数组,其中每个元素都是带有 CSS 属性-值对的字符串。此方法逐个列或行传递您的 DataFrame,或者一次传递整个表格,具体取决于
axis
关键字参数。对于列向使用axis=0
,对于行向使用axis=1
,对于整个表格同时使用axis=None
。
此方法适用于对数据单元应用多个复杂逻辑。我们创建一个新的 DataFrame 来演示这一点。
[22]:
np.random.seed(0)
df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
df2.style
[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 |
例如,我们可以构建一个函数,如果文本为负数则着色,并将其与一个部分淡化微不足道值的单元格的函数链接起来。由于这是逐个元素处理的,我们使用map
。
[23]:
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
[23]:
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 中的最大值。在这种情况下,我们使用apply
。下面我们突出显示了一列中的最大值。
[25]:
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)
[25]:
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 中的最大值为紫色,行最大值为粉色。
[27]:
s2.apply(highlight_max, props='color:white;background-color:pink;', axis=1)\
.apply(highlight_max, props='color:white;background-color:purple', axis=None)
[27]:
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 |
这个最后的例子展示了一些样式被其他样式覆盖的情况。一般来说,最近应用的样式是有效的,但你可以在 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
应用程序。
[29]:
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)
[29]:
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,呈现 CSS 样式。
-
.map()(逐元素):接受一个接受单个值并返回带有 CSS 属性-值对的字符串的函数。
-
.apply()(列-/行-/表格级):接受一个接受 Series 或 DataFrame 并返回具有相同形状的 Series、DataFrame 或 numpy 数组的函数,其中每个元素都是带有 CSS 属性-值对的字符串。此方法逐个传递您的 DataFrame 的每一列或行,或者根据
axis
关键字参数一次传递整个表格。对于按列使用axis=0
,按行使用axis=1
,对于一次传递整个表格使用axis=None
。
此方法可用于对数据单元应用多个复杂逻辑。我们创建一个新的 DataFrame 来演示这一点。
[22]:
np.random.seed(0)
df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
df2.style
[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 |
例如,我们可以构建一个函数,如果文本为负数则着色,并将其与一个部分淡化微不足道值的函数链接。由于这是逐个元素查看,我们使用map
。
[23]:
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
[23]:
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 |
我们还可以构建一个函数,一次性突出显示行、列和整个数据框中的最大值。在这种情况下,我们使用apply
。下面我们突出显示一列中的最大值。
[25]:
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)
[25]:
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 |
我们可以在不同的轴上使用相同的函数,这里突出显示数据框中的最大值为紫色,行最大值为粉色。
[27]:
s2.apply(highlight_max, props='color:white;background-color:pink;', axis=1)\
.apply(highlight_max, props='color:white;background-color:purple', axis=None)
[27]:
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 |
这个最后的例子展示了一些样式被其他样式覆盖的情况。一般来说,最近应用的样式是活动的,但你可以在 CSS 层级结构部分中了解更多。你也可以将这些样式应用于数据框的更细粒度部分 - 在子集切片部分中了解更多。
只使用类可以复制部分此功能,但可能更加繁琐。请参见优化的第 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
应用程序。
[29]:
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)
[29]:
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。
[30]:
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)
[30]:
多个癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
添加工具提示(自版本 1.3.0 起)可以使用 .set_tooltips() 方法来完成,方式与您可以通过提供基于字符串的 DataFrame 来为数据单元格添加 CSS 类名相同。您不必为工具提示指定css_class
名称或任何 cssprops
,因为有标准默认值,但如果您想要更多的视觉控制,可以选择该选项。
[32]:
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;')
[32]:
多个癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测值: | ��瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
我们表格中唯一剩下的事情就是添加突出显示的边框,以吸引观众注意力到工具提示上。我们将像之前一样使用表格样式创建内部 CSS 类。设置类总是会覆盖,所以我们需要确保添加之前的类。
[34]:
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)
[34]:
多个癌症预测模型的混淆矩阵。
模型: | 决策树 | 回归 |
---|---|---|
预测值: | 肿瘤 | 非肿瘤 |
--- | --- | --- |
实际标签: | ||
--- | --- | --- |
肿瘤(阳性) | 38 | 2 |
非肿瘤(阴性) | 19 | 439 |
使用切片进行更精细的控制
到目前为止,我们展示的Styler.apply
和Styler.map
函数的示例还没有展示subset
参数的使用。这是一个很有用的参数,它允许很多灵活性:它允许您对特定行或列应用样式,而无需将该逻辑编码到您的style
函数中。
传递给subset
的值类似于对 DataFrame 进行切片;
-
标量被视为列标签
-
列表(或 Series 或 NumPy 数组)被视为多个列标签
-
元组被视为
(行索引器,列索引器)
考虑使用pd.IndexSlice
来构建最后一个元组。我们将创建一个多级索引的 DataFrame 来展示其功能。
[36]:
df3 = pd.DataFrame(np.random.randn(4,4),
pd.MultiIndex.from_product([['A', 'B'], ['r1', 'r2']]),
columns=['c1','c2','c3','c4'])
df3
[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 |
我们将使用 subset 来突出显示第三和第四列中的最大值,并使用红色文本。我们将用黄色突出显示切片区域。
[37]:
slice_ = ['c3', '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 | -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
结合使用,它可以更灵活地跨越两个维度进行索引。
[38]:
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_)
[38]:
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
中使用时对行进行子选择的灵活性。
[39]:
slice_ = idx[idx[:,'r2'], :]
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 | -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 |
还有提供条件过滤的余地。
假设我们想要在仅在列 2 和 4 的情况下突出显示最大值,只要列 1 和 3 的总和小于 -2.0 (基本上排除行 (:,'r2')
)*。
[40]:
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_)
[40]:
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 |
目前仅支持基于标签的切片,不支持位置切片,也不支持可调用对象。
如果您的样式函数使用 subset
或 axis
关键字参数,请考虑将函数包装在 functools.partial
中,将该关键字部分化。
my_func2 = functools.partial(my_func, subset=42)
优化
一般来说,对于较小的表格和大多数情况,渲染的 HTML 不需要优化,我们也不建议这样做。有两种情况值得考虑:
-
渲染和设计非常庞大的 HTML 表格时,某些浏览器会出现性能问题。
-
如果您正在使用
Styler
动态创建在线用户界面的一部分,并且希望提高网络性能。
在这里,我们建议采取以下步骤实现:
1. 删除 UUID 和单元格 ID
忽略 uuid
并将 cell_ids
设置为 False
。这将防止不必要的 HTML。
这是次优的:
[41]:
df4 = pd.DataFrame([[1,2],[3,4]])
s4 = df4.style
这更好:
[42]:
from pandas.io.formats.style import Styler
s4 = Styler(df4, uuid_len=0, cell_ids=False)
2. 使用表格样式
在可能的情况下使用表格样式(例如一次为所有单元格或行或列),因为 CSS 几乎总是比其他格式更高效。
这是次优的:
[43]:
props = 'font-family: "Times New Roman", Times, serif; color: #e83e8c; font-size:1.3em;'
df4.style.map(lambda x: props, subset=[1])
[43]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
这更好:
[44]:
df4.style.set_table_styles([{'selector': 'td.col1', 'props': props}])
[44]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
3. 设置类,而不是使用 Styler 函数
对于应用相同样式于许多单元格的大型数据帧,将样式声明为类,然后将这些类应用于数据单元格可能更有效,而不是直接将样式应用于单元格。然而,当您不关心优化时,使用 Styler 函数 api 可能更容易。
这是次优的:
[45]:
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)
[45]:
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 |
这更好:
[46]:
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)
[46]:
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. 如果每个字节都很重要,请使用字符串替换
您可以通过替换默认 CSS 字典来移除不必要的 HTML,或者缩短默认类名。您可以在 下文 了解更多有关 CSS 的信息。
[47]:
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" > </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>
[48]:
html
[48]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
1. 移除 UUID 和 cell_ids
忽略 uuid
并将 cell_ids
设置为 False
。这样可以避免生成不必要的 HTML。
这是次优的:
[41]:
df4 = pd.DataFrame([[1,2],[3,4]])
s4 = df4.style
这是更好的:
[42]:
from pandas.io.formats.style import Styler
s4 = Styler(df4, uuid_len=0, cell_ids=False)
2. 使用表格样式
在可能的情况下使用表格样式(例如,一次为所有单元格、行或列)会更有效,因为 CSS 几乎总是比其他格式更高效。
这是次优的:
[43]:
props = 'font-family: "Times New Roman", Times, serif; color: #e83e8c; font-size:1.3em;'
df4.style.map(lambda x: props, subset=[1])
[43]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
这是更好的:
[44]:
df4.style.set_table_styles([{'selector': 'td.col1', 'props': props}])
[44]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
3. 设置类而不是使用 Styler 函数
对于大型数据框,如果对许多单元格应用相同的样式,将样式声明为类,然后将这些类应用于数据单元格可能更有效,而不是直接将样式应用于单元格。然而,如果您不关心优化,直接使用 Styler 函数 api 可能更容易。
这是次优的:
[45]:
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)
[45]:
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 |
这是更好的:
[46]:
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)
[46]:
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. 如果每个字节都很重要,请使用字符串替换。
您可以通过替换默认的 CSS 字典来删除不必要的 HTML,或者缩短默认类名。您可以在下面稍微了解一下 CSS。
[47]:
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" > </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>
[48]:
html
[48]:
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
内置样式
一些样式函数非常常见,我们已经“内置”到 Styler
中,所以您不必自己编写并应用它们。目前这样的函数列表如下:
-
.highlight_null:用于识别缺失数据。
-
.highlight_min 和 .highlight_max:用于识别数据极值的功能。
-
.highlight_between 和 .highlight_quantile:用于识别数据内的类别。
-
.background_gradient:根据数值范围高亮单元格的灵活方法。
-
.text_gradient:类似的方法,根据数值范围高亮文本。
-
.bar:在单元格背景中显示迷你图表。
每个函数的具体文档通常会提供更多的参数示例。
强调空值
[49]:
df2.iloc[0,2] = np.nan
df2.iloc[4,3] = np.nan
df2.loc[:4].style.highlight_null(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 |
强调最小值或最大值
[50]:
df2.loc[:4].style.highlight_max(axis=1, props='color:white; font-weight:bold; background-color:darkblue;')
[50]:
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 |
强调之间
该方法接受浮点数范围,或者如果索引匹配,还可以接受 NumPy 数组或 Series。
[51]:
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;')
[51]:
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 |
强调分位数
用于检测最高或最低百分位数值
[52]:
df2.loc[:4].style.highlight_quantile(q_left=0.85, axis=None, color='yellow')
[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 |
背景渐变和文本渐变
您可以使用background_gradient
和text_gradient
方法创建“热图”。这需要 matplotlib,并且我们将使用Seaborn来获得漂亮的颜色映射。
[53]:
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
df2.style.background_gradient(cmap=cm)
[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 |
[54]:
df2.style.text_gradient(cmap=cm)
[54]:
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 |
.background_gradient 和.text_gradient 有许多关键字参数可自定义渐变和颜色。请参阅文档。
设置属性
使用Styler.set_properties
当样式实际上并不依赖于数值时。这只是一个简单的.map
的包装,其中函数为所有单元格返回相同的属性。
[55]:
df2.loc[:4].style.set_properties(**{'background-color': 'black',
'color': 'lawngreen',
'border-color': 'white'})
[55]:
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 中包含“条形图”。
[56]:
df2.style.bar(subset=['A', 'B'], color='#d65f5f')
[56]:
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 colormap。
展示一个示例,这里是如何使用新的align
选项来改变上述内容的,结合设置vmin
和vmax
限制,图形的width
,以及单元格的底层 cssprops
,留出空间来显示文本和条形。我们还使用text_gradient
来使用 matplotlib colormap 将文本着色为与条形相同的颜色(尽管在这种情况下,可能最好不使用这种额外效果)。
[57]:
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)
[57]:
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 |
以下示例旨在突出新对齐选项的行为:
[59]:
HTML(head)
[59]:
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 |
|
Highlight Null
[49]:
df2.iloc[0,2] = np.nan
df2.iloc[4,3] = np.nan
df2.loc[:4].style.highlight_null(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 |
Highlight Min or Max
[50]:
df2.loc[:4].style.highlight_max(axis=1, props='color:white; font-weight:bold; background-color:darkblue;')
[50]:
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 |
Highlight Between
此方法接受浮点数范围,或者 NumPy 数组或 Series,只要索引匹配。
[51]:
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;')
[51]:
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 |
Highlight Quantile
用于检测最高或最低百分位值
[52]:
df2.loc[:4].style.highlight_quantile(q_left=0.85, axis=None, color='yellow')
[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 |
背景渐变和文本渐变
您可以使用background_gradient
和text_gradient
方法创建“热图”。这些需要 matplotlib,我们将使用Seaborn来获得漂亮的颜色映射。
[53]:
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
df2.style.background_gradient(cmap=cm)
[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 |
[54]:
df2.style.text_gradient(cmap=cm)
[54]:
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 |
.background_gradient 和 .text_gradient 有许多关键字参数可用于自定义渐变和颜色。请参阅文档。
设置属性
当样式实际上不依赖于值时,请使用Styler.set_properties
。这只是一个简单的.map
的包装器,其中函数为所有单元格返回相同的属性。
[55]:
df2.loc[:4].style.set_properties(**{'background-color': 'black',
'color': 'lawngreen',
'border-color': 'white'})
[55]:
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 中包含“条形图”。
[56]:
df2.style.bar(subset=['A', 'B'], color='#d65f5f')
[56]:
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
选项来更改上述内容,结合设置vmin
和vmax
限制,图形的width
,以及单元格的底层 css props
,留出空间来显示文本和条形图。我们还使用text_gradient
来使用 matplotlib 颜色映射对文本着色,尽管在这种情况下,可能最好不使用这种额外效果。
[57]:
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)
[57]:
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 |
以下示例旨在突出新对齐选项的行为:
[59]:
HTML(head)
[59]:
对齐 | 全负 | 正负混合 | 全正 | 大正数 |
---|---|---|---|---|
左对齐 |
| |
| --- |
| -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
导出样式,并使用df1.style.set
在第二个 DataFrame 上导入样式
[60]:
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
[60]:
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 |
[61]:
style2 = df3.style
style2.use(style1.export())
style2
[61]:
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 优化
-
您只能应用样式,不能插入新的 HTML 实体,除非通过子类化。
其他有趣且有用的东西
这里有一些有趣的例子。
小部件
Styler
与小部件的互动效果相当不错。如果您在线查看而不是自己运行笔记本,则无法交互地调整调色板。
[62]:
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)
)
放大
[63]:
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')])
]
[64]:
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())
[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 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0.23 | 1.03 | -0.84 | -0.59 | -0.96 | -0.22 | -0.62 | 1.84 | -2.05 | 0.87 | -0.92 | -0.23 | 2.15 | -1.33 | 0.08 | -1.25 | 1.20 | -1.05 | 1.06 | -0.42 | 2.29 | -2.59 | 2.82 | 0.68 | -1.58 |
1 | -1.75 | 1.56 | -1.13 | -1.10 | 1.03 | 0.00 | -2.46 | 3.45 | -1.66 | 1.27 | -0.52 | -0.02 | 1.52 | -1.09 | -1.86 | -1.13 | -0.68 | -0.81 | 0.35 | -0.06 | 1.79 | -2.82 | 2.26 | 0.78 | 0.44 |
2 | -0.65 | 3.22 | -1.76 | 0.52 | 2.20 | -0.37 | -3.00 | 3.73 | -1.87 | 2.46 | 0.21 | -0.24 | -0.10 | -0.78 | -3.02 | -0.82 | -0.21 | -0.23 | 0.86 | -0.68 | 1.45 | -4.89 | 3.03 | 1.91 | 0.61 |
3 | -1.62 | 3.71 | -2.31 | 0.43 | 4.17 | -0.43 | -3.86 | 4.16 | -2.15 | 1.08 | 0.12 | 0.60 | -0.89 | 0.27 | -3.67 | -2.71 | -0.31 | -1.59 | 1.35 | -1.83 | 0.91 | -5.80 | 2.81 | 2.11 | 0.28 |
4 | -3.35 | 4.48 | -1.86 | -1.70 | 5.19 | -1.02 | -3.81 | 4.72 | -0.72 | 1.08 | -0.18 | 0.83 | -0.22 | -1.08 | -4.27 | -2.88 | -0.97 | -1.78 | 1.53 | -1.80 | 2.21 | -6.34 | 3.34 | 2.49 | 2.09 |
5 | -0.84 | 4.23 | -1.65 | -2.00 | 5.34 | -0.99 | -4.13 | 3.94 | -1.06 | -0.94 | 1.24 | 0.09 | -1.78 | -0.11 | -4.45 | -0.85 | -2.06 | -1.35 | 0.80 | -1.63 | 1.54 | -6.51 | 2.80 | 2.14 | 3.77 |
6 | -0.74 | 5.35 | -2.11 | -1.13 | 4.20 | -1.85 | -3.20 | 3.76 | -3.22 | -1.23 | 0.34 | 0.57 | -1.82 | 0.54 | -4.43 | -1.83 | -4.03 | -2.62 | -0.20 | -4.68 | 1.93 | -8.46 | 3.34 | 2.52 | 5.81 |
7 | -0.44 | 4.69 | -2.30 | -0.21 | 5.93 | -2.63 | -1.83 | 5.46 | -4.50 | -3.16 | -1.73 | 0.18 | 0.11 | 0.04 | -5.99 | -0.45 | -6.20 | -3.89 | 0.71 | -3.95 | 0.67 | -7.26 | 2.97 | 3.39 | 6.66 |
8 | 0.92 | 5.80 | -3.33 | -0.65 | 5.99 | -3.19 | -1.83 | 5.63 | -3.53 | -1.30 | -1.61 | 0.82 | -2.45 | -0.40 | -6.06 | -0.52 | -6.60 | -3.48 | -0.04 | -4.60 | 0.51 | -5.85 | 3.23 | 2.40 | 5.08 |
9 | 0.38 | 5.54 | -4.49 | -0.80 | 7.05 | -2.64 | -0.44 | 5.35 | -1.96 | -0.33 | -0.80 | 0.26 | -3.37 | -0.82 | -6.05 | -2.61 | -8.45 | -4.45 | 0.41 | -4.71 | 1.89 | -6.93 | 2.14 | 3.00 | 5.16 |
10 | 2.06 | 5.84 | -3.90 | -0.98 | 7.78 | -2.49 | -0.59 | 5.59 | -2.22 | -0.71 | -0.46 | 1.80 | -2.79 | 0.48 | -5.97 | -3.44 | -7.77 | -5.49 | -0.70 | -4.61 | -0.52 | -7.72 | 1.54 | 5.02 | 5.81 |
11 | 1.86 | 4.47 | -2.17 | -1.38 | 5.90 | -0.49 | 0.02 | 5.78 | -1.04 | -0.60 | 0.49 | 1.96 | -1.47 | 1.88 | -5.92 | -4.55 | -8.15 | -3.42 | -2.24 | -4.33 | -1.17 | -7.90 | 1.36 | 5.31 | 5.83 |
12 | 3.19 | 4.22 | -3.06 | -2.27 | 5.93 | -2.64 | 0.33 | 6.72 | -2.84 | -0.20 | 1.89 | 2.63 | -1.53 | 0.75 | -5.27 | -4.53 | -7.57 | -2.85 | -2.17 | -4.78 | -1.13 | -8.99 | 2.11 | 6.42 | 5.60 |
13 | 2.31 | 4.45 | -3.87 | -2.05 | 6.76 | -3.25 | -2.17 | 7.99 | -2.56 | -0.80 | 0.71 | 2.33 | -0.16 | -0.46 | -5.10 | -3.79 | -7.58 | -4.00 | 0.33 | -3.67 | -1.05 | -8.71 | 2.47 | 5.87 | 6.71 |
14 | 3.78 | 4.33 | -3.88 | -1.58 | 6.22 | -3.23 | -1.46 | 5.57 | -2.93 | -0.33 | -0.97 | 1.72 | 3.61 | 0.29 | -4.21 | -4.10 | -6.68 | -4.50 | -2.19 | -2.43 | -1.64 | -9.36 | 3.36 | 6.11 | 7.53 |
15 | 5.64 | 5.31 | -3.98 | -2.26 | 5.91 | -3.30 | -1.03 | 5.68 | -3.06 | -0.33 | -1.16 | 2.19 | 4.20 | 1.01 | -3.22 | -4.31 | -5.74 | -4.44 | -2.30 | -1.36 | -1.20 | -11.27 | 2.59 | 6.69 | 5.91 |
16 | 4.08 | 4.34 | -2.44 | -3.30 | 6.04 | -2.52 | -0.47 | 5.28 | -4.84 | 1.58 | 0.23 | 0.10 | 5.79 | 1.80 | -3.13 | -3.85 | -5.53 | -2.97 | -2.13 | -1.15 | -0.56 | -13.13 | 2.07 | 6.16 | 4.94 |
17 | 5.64 | 4.57 | -3.53 | -3.76 | 6.58 | -2.58 | -0.75 | 6.58 | -4.78 | 3.63 | -0.29 | 0.56 | 5.76 | 2.05 | -2.27 | -2.31 | -4.95 | -3.16 | -3.06 | -2.43 | 0.84 | -12.57 | 3.56 | 7.36 | 4.70 |
18 | 5.99 | 5.82 | -2.85 | -4.15 | 7.12 | -3.32 | -1.21 | 7.93 | -4.85 | 1.44 | -0.63 | 0.35 | 7.47 | 0.87 | -1.52 | -2.09 | -4.23 | -2.55 | -2.46 | -2.89 | 1.90 | -9.74 | 3.43 | 7.07 | 4.39 |
19 | 4.03 | 6.23 | -4.10 | -4.11 | 7.19 | -4.10 | -1.52 | 6.53 | -5.21 | -0.24 | 0.01 | 1.16 | 6.43 | -1.97 | -2.64 | -1.66 | -5.20 | -3.25 | -2.87 | -1.65 | 1.64 | -10.66 | 2.83 | 7.48 | 3.94 |
粘性标题
如果您在笔记本中显示一个大型矩阵或数据框,但是希望始终看到列和行标题,可以使用.set_sticky 方法,该方法操作表格样式的 CSS。
[65]:
bigdf = pd.DataFrame(np.random.randn(16, 100))
bigdf.style.set_sticky(axis="index")
[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 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | -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 |
| 1 | 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 |
| 2 | 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 |
| 3 | -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 |
| 4 | -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 |
| 5 | -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 |
| 6 | 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 |
| 7 | 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 |
| 8 | -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 |
| 9 | -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 |
| 10 | -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 |
| 11 | -0.625210 | 0.288911 | 0.288374 | -1.372667 | -0.591395 | -0.478942 | 1.335664 | -0.459855 | -1.615975 | -1.189676 | 0.374767 | -2.488733 | 0.586656 | -1.422008 | 0.496030 | 1.911128 | -0.560660 | -0.499614 | -0.372171 | -1.833069 | 0.237124 | -0.944446 | 0.912140 | 0.359790 | -1.359235 | 0.166966 | -0.047107 | -0.279789 | -0.594454 | -0.739013 | -1.527645 | 0.401668 | 1.791252 | -2.774848 | 0.523873 | 2.207585 | 0.488999 | -0.339283 | 0.131711 | 0.018409 | 1.186551 | -0.424318 | 1.554994 | -0.205917 | -0.934975 | 0.654102 | -1.227761 | -0.461025 | -0.421201 | -0.058615 | -0.584563 | 0.336913 | -0.477102 | -1.381463 | 0.757745 | -0.268968 | 0.034870 | 1.231686 | 0.236600 | 1.234720 | -0.040247 | 0.029582 | 1.034905 | 0.380204 | -0.012108 | -0.859511 | -0.990340 | -1.205172 | -1.030178 | 0.426676 | 0.497796 | -0.876808 | 0.957963 | 0.173016 | 0.131612 | -1.003556 | -1.069908 | -1.799207 | 1.429598 | -0.116015 | -1.454980 | 0.261917 | 0.444412 | 0.273290 | 0.844115 | 0.218745 | -1.033350 | -1.188295 | 0.058373 | 0.800523 | -1.627068 | 0.861651 | 0.871018 | -0.003733 | -0.243354 | 0.947296 | 0.509406 | 0.044546 | 0.266896 | 1.337165 |
| 12 | 0.699142 | -1.928033 | 0.105363 | 1.042322 | 0.715206 | -0.763783 | 0.098798 | -1.157898 | 0.134105 | 0.042041 | 0.674826 | 0.165649 | -1.622970 | -3.131274 | 0.597649 | -1.880331 | 0.663980 | -0.256033 | -1.524058 | 0.492799 | 0.221163 | 0.429622 | -0.659584 | 1.264506 | -0.032131 | -2.114907 | -0.264043 | 0.457835 | -0.676837 | -0.629003 | 0.489145 | -0.551686 | 0.942622 | -0.512043 | -0.455893 | 0.021244 | -0.178035 | -2.498073 | -0.171292 | 0.323510 | -0.545163 | -0.668909 | -0.150031 | 0.521620 | -0.428980 | 0.676463 | 0.369081 | -0.724832 | 0.793542 | 1.237422 | 0.401275 | 2.141523 | 0.249012 | 0.486755 | -0.163274 | 0.592222 | -0.292600 | -0.547168 | 0.619104 | -0.013605 | 0.776734 | 0.131424 | 1.189480 | -0.666317 | -0.939036 | 1.105515 | 0.621452 | 1.586605 | -0.760970 | 1.649646 | 0.283199 | 1.275812 | -0.452012 | 0.301361 | -0.976951 | -0.268106 | -0.079255 | -1.258332 | 2.216658 | -1.175988 | -0.863497 | -1.653022 | -0.561514 | 0.450753 | 0.417200 | 0.094676 | -2.231054 | 1.316862 | -0.477441 | 0.646654 | -0.200252 | 1.074354 | -0.058176 | 0.120990 | 0.222522 | -0.179507 | 0.421655 | -0.914341 | -0.234178 | 0.741524 |
| 13 | 0.932714 | 1.423761 | -1.280835 | 0.347882 | -0.863171 | -0.852580 | 1.044933 | 2.094536 | 0.806206 | 0.416201 | -1.109503 | 0.145302 | -0.996871 | 0.325456 | -0.605081 | 1.175326 | 1.645054 | 0.293432 | -2.766822 | 1.032849 | 0.079115 | -1.414132 | 1.463376 | 2.335486 | 0.411951 | -0.048543 | 0.159284 | -0.651554 | -1.093128 | 1.568390 | -0.077807 | -2.390779 | -0.842346 | -0.229675 | -0.999072 | -1.367219 | -0.792042 | -1.878575 | 1.451452 | 1.266250 | -0.734315 | 0.266152 | 0.735523 | -0.430860 | 0.229864 | 0.850083 | -2.241241 | 1.063850 | 0.289409 | -0.354360 | 0.113063 | -0.173006 | 1.386998 | 1.886236 | 0.587119 | -0.961133 | 0.399295 | 1.461560 | 0.310823 | 0.280220 | -0.879103 | -1.326348 | 0.003337 | -1.085908 | -0.436723 | 2.111926 | 0.106068 | 0.615597 | 2.152996 | -0.196155 | 0.025747 | -0.039061 | 0.656823 | -0.347105 | 2.513979 | 1.758070 | 1.288473 | -0.739185 | -0.691592 | -0.098728 | -0.276386 | 0.489981 | 0.516278 | -0.838258 | 0.596673 | -0.331053 | 0.521174 | -0.145023 | 0.836693 | -1.092166 | 0.361733 | -1.169981 | 0.046731 | 0.655377 | -0.756852 | 1.285805 | -0.095019 | 0.360253 | 1.370621 | 0.083010 |
| 14 | 0.888893 | 2.288725 | -1.032332 | 0.212273 | -1.091826 | 1.692498 | 1.025367 | 0.550854 | 0.679430 | -1.335712 | -0.798341 | 2.265351 | -1.006938 | 2.059761 | 0.420266 | -1.189657 | 0.506674 | 0.260847 | -0.533145 | 0.727267 | 1.412276 | 1.482106 | -0.996258 | 0.588641 | -0.412642 | -0.920733 | -0.874691 | 0.839002 | 0.501668 | -0.342493 | -0.533806 | -2.146352 | -0.597339 | 0.115726 | 0.850683 | -0.752239 | 0.377263 | -0.561982 | 0.262783 | -0.356676 | -0.367462 | 0.753611 | -1.267414 | -1.330698 | -0.536453 | 0.840938 | -0.763108 | -0.268100 | -0.677424 | 1.606831 | 0.151732 | -2.085701 | 1.219296 | 0.400863 | 0.591165 | -1.485213 | 1.501979 | 1.196569 | -0.214154 | 0.339554 | -0.034446 | 1.176452 | 0.546340 | -1.255630 | -1.309210 | -0.445437 | 0.189437 | -0.737463 | 0.843767 | -0.605632 | -0.060777 | 0.409310 | 1.285569 | -0.622638 | 1.018193 | 0.880680 | 0.046805 | -1.818058 | -0.809829 | 0.875224 | 0.409569 | -0.116621 | -1.238919 | 3.305724 | -0.024121 | -1.756500 | 1.328958 | 0.507593 | -0.866554 | -2.240848 | -0.661376 | -0.671824 | 0.215720 | -0.296326 | 0.481402 | 0.829645 | -0.721025 | 1.263914 | 0.549047 | -1.234945 |
| 15 | -1.978838 | 0.721823 | -0.559067 | -1.235243 | 0.420716 | -0.598845 | 0.359576 | -0.619366 | -1.757772 | -1.156251 | 0.705212 | 0.875071 | -1.020376 | 0.394760 | -0.147970 | 0.230249 | 1.355203 | 1.794488 | 2.678058 | -0.153565 | -0.460959 | -0.098108 | -1.407930 | -2.487702 | 1.823014 | 0.099873 | -0.517603 | -0.509311 | -1.833175 | -0.900906 | 0.459493 | -0.655440 | 1.466122 | -1.531389 | -0.422106 | 0.421422 | 0.578615 | 0.259795 | 0.018941 | -0.168726 | 1.611107 | -1.586550 | -1.384941 | 0.858377 | 1.033242 | 1.701343 | 1.748344 | -0.371182 | -0.843575 | 2.089641 | -0.345430 | -1.740556 | 0.141915 | -2.197138 | 0.689569 | -0.150025 | 0.287456 | 0.654016 | -1.521919 | -0.918008 | -0.587528 | 0.230636 | 0.262637 | 0.615674 | 0.600044 | -0.494699 | -0.743089 | 0.220026 | -0.242207 | 0.528216 | -0.328174 | -1.536517 | -1.476640 | -1.162114 | -1.260222 | 1.106252 | -1.467408 | -0.349341 | -1.841217 | 0.031296 | -0.076475 | -0.353383 | 0.807545 | 0.779064 | -2.398417 | -0.267828 | 1.549734 | 0.814397 | 0.284770 | -0.659369 | 0.761040 | -0.722067 | 0.810332 | 1.501295 | 1.440865 | -1.367459 | -0.700301 | -1.540662 | 0.159837 | -0.625415 |
也可以粘贴多级索引,甚至只有特定级别。
[66]:
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])
[66]:
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.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 |
1 | 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 | ||
2 | 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 | ||
3 | -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 | -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 | |
1 | -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 | ||
2 | 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 | ||
3 | 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 | ||
B | 0 | 0 | -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 |
1 | -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 | ||
2 | -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 | ||
3 | -0.625210 | 0.288911 | 0.288374 | -1.372667 | -0.591395 | -0.478942 | 1.335664 | -0.459855 | -1.615975 | -1.189676 | 0.374767 | -2.488733 | 0.586656 | -1.422008 | 0.496030 | 1.911128 | -0.560660 | -0.499614 | -0.372171 | -1.833069 | 0.237124 | -0.944446 | 0.912140 | 0.359790 | -1.359235 | 0.166966 | -0.047107 | -0.279789 | -0.594454 | -0.739013 | -1.527645 | 0.401668 | 1.791252 | -2.774848 | 0.523873 | 2.207585 | 0.488999 | -0.339283 | 0.131711 | 0.018409 | 1.186551 | -0.424318 | 1.554994 | -0.205917 | -0.934975 | 0.654102 | -1.227761 | -0.461025 | -0.421201 | -0.058615 | -0.584563 | 0.336913 | -0.477102 | -1.381463 | 0.757745 | -0.268968 | 0.034870 | 1.231686 | 0.236600 | 1.234720 | -0.040247 | 0.029582 | 1.034905 | 0.380204 | -0.012108 | -0.859511 | -0.990340 | -1.205172 | -1.030178 | 0.426676 | 0.497796 | -0.876808 | 0.957963 | 0.173016 | 0.131612 | -1.003556 | -1.069908 | -1.799207 | 1.429598 | -0.116015 | -1.454980 | 0.261917 | 0.444412 | 0.273290 | 0.844115 | 0.218745 | -1.033350 | -1.188295 | 0.058373 | 0.800523 | -1.627068 | 0.861651 | 0.871018 | -0.003733 | -0.243354 | 0.947296 | 0.509406 | 0.044546 | 0.266896 | 1.337165 | ||
1 | 0 | 0.699142 | -1.928033 | 0.105363 | 1.042322 | 0.715206 | -0.763783 | 0.098798 | -1.157898 | 0.134105 | 0.042041 | 0.674826 | 0.165649 | -1.622970 | -3.131274 | 0.597649 | -1.880331 | 0.663980 | -0.256033 | -1.524058 | 0.492799 | 0.221163 | 0.429622 | -0.659584 | 1.264506 | -0.032131 | -2.114907 | -0.264043 | 0.457835 | -0.676837 | -0.629003 | 0.489145 | -0.551686 | 0.942622 | -0.512043 | -0.455893 | 0.021244 | -0.178035 | -2.498073 | -0.171292 | 0.323510 | -0.545163 | -0.668909 | -0.150031 | 0.521620 | -0.428980 | 0.676463 | 0.369081 | -0.724832 | 0.793542 | 1.237422 | 0.401275 | 2.141523 | 0.249012 | 0.486755 | -0.163274 | 0.592222 | -0.292600 | -0.547168 | 0.619104 | -0.013605 | 0.776734 | 0.131424 | 1.189480 | -0.666317 | -0.939036 | 1.105515 | 0.621452 | 1.586605 | -0.760970 | 1.649646 | 0.283199 | 1.275812 | -0.452012 | 0.301361 | -0.976951 | -0.268106 | -0.079255 | -1.258332 | 2.216658 | -1.175988 | -0.863497 | -1.653022 | -0.561514 | 0.450753 | 0.417200 | 0.094676 | -2.231054 | 1.316862 | -0.477441 | 0.646654 | -0.200252 | 1.074354 | -0.058176 | 0.120990 | 0.222522 | -0.179507 | 0.421655 | -0.914341 | -0.234178 | 0.741524 | |
1 | 0.932714 | 1.423761 | -1.280835 | 0.347882 | -0.863171 | -0.852580 | 1.044933 | 2.094536 | 0.806206 | 0.416201 | -1.109503 | 0.145302 | -0.996871 | 0.325456 | -0.605081 | 1.175326 | 1.645054 | 0.293432 | -2.766822 | 1.032849 | 0.079115 | -1.414132 | 1.463376 | 2.335486 | 0.411951 | -0.048543 | 0.159284 | -0.651554 | -1.093128 | 1.568390 | -0.077807 | -2.390779 | -0.842346 | -0.229675 | -0.999072 | -1.367219 | -0.792042 | -1.878575 | 1.451452 | 1.266250 | -0.734315 | 0.266152 | 0.735523 | -0.430860 | 0.229864 | 0.850083 | -2.241241 | 1.063850 | 0.289409 | -0.354360 | 0.113063 | -0.173006 | 1.386998 | 1.886236 | 0.587119 | -0.961133 | 0.399295 | 1.461560 | 0.310823 | 0.280220 | -0.879103 | -1.326348 | 0.003337 | -1.085908 | -0.436723 | 2.111926 | 0.106068 | 0.615597 | 2.152996 | -0.196155 | 0.025747 | -0.039061 | 0.656823 | -0.347105 | 2.513979 | 1.758070 | 1.288473 | -0.739185 | -0.691592 | -0.098728 | -0.276386 | 0.489981 | 0.516278 | -0.838258 | 0.596673 | -0.331053 | 0.521174 | -0.145023 | 0.836693 | -1.092166 | 0.361733 | -1.169981 | 0.046731 | 0.655377 | -0.756852 | 1.285805 | -0.095019 | 0.360253 | 1.370621 | 0.083010 | ||
2 | 0.888893 | 2.288725 | -1.032332 | 0.212273 | -1.091826 | 1.692498 | 1.025367 | 0.550854 | 0.679430 | -1.335712 | -0.798341 | 2.265351 | -1.006938 | 2.059761 | 0.420266 | -1.189657 | 0.506674 | 0.260847 | -0.533145 | 0.727267 | 1.412276 | 1.482106 | -0.996258 | 0.588641 | -0.412642 | -0.920733 | -0.874691 | 0.839002 | 0.501668 | -0.342493 | -0.533806 | -2.146352 | -0.597339 | 0.115726 | 0.850683 | -0.752239 | 0.377263 | -0.561982 | 0.262783 | -0.356676 | -0.367462 | 0.753611 | -1.267414 | -1.330698 | -0.536453 | 0.840938 | -0.763108 | -0.268100 | -0.677424 | 1.606831 | 0.151732 | -2.085701 | 1.219296 | 0.400863 | 0.591165 | -1.485213 | 1.501979 | 1.196569 | -0.214154 | 0.339554 | -0.034446 | 1.176452 | 0.546340 | -1.255630 | -1.309210 | -0.445437 | 0.189437 | -0.737463 | 0.843767 | -0.605632 | -0.060777 | 0.409310 | 1.285569 | -0.622638 | 1.018193 | 0.880680 | 0.046805 | -1.818058 | -0.809829 | 0.875224 | 0.409569 | -0.116621 | -1.238919 | 3.305724 | -0.024121 | -1.756500 | 1.328958 | 0.507593 | -0.866554 | -2.240848 | -0.661376 | -0.671824 | 0.215720 | -0.296326 | 0.481402 | 0.829645 | -0.721025 | 1.263914 | 0.549047 | -1.234945 | ||
3 | -1.978838 | 0.721823 | -0.559067 | -1.235243 | 0.420716 | -0.598845 | 0.359576 | -0.619366 | -1.757772 | -1.156251 | 0.705212 | 0.875071 | -1.020376 | 0.394760 | -0.147970 | 0.230249 | 1.355203 | 1.794488 | 2.678058 | -0.153565 | -0.460959 | -0.098108 | -1.407930 | -2.487702 | 1.823014 | 0.099873 | -0.517603 | -0.509311 | -1.833175 | -0.900906 | 0.459493 | -0.655440 | 1.466122 | -1.531389 | -0.422106 | 0.421422 | 0.578615 | 0.259795 | 0.018941 | -0.168726 | 1.611107 | -1.586550 | -1.384941 | 0.858377 | 1.033242 | 1.701343 | 1.748344 | -0.371182 | -0.843575 | 2.089641 | -0.345430 | -1.740556 | 0.141915 | -2.197138 | 0.689569 | -0.150025 | 0.287456 | 0.654016 | -1.521919 | -0.918008 | -0.587528 | 0.230636 | 0.262637 | 0.615674 | 0.600044 | -0.494699 | -0.743089 | 0.220026 | -0.242207 | 0.528216 | -0.328174 | -1.536517 | -1.476640 | -1.162114 | -1.260222 | 1.106252 | -1.467408 | -0.349341 | -1.841217 | 0.031296 | -0.076475 | -0.353383 | 0.807545 | 0.779064 | -2.398417 | -0.267828 | 1.549734 | 0.814397 | 0.284770 | -0.659369 | 0.761040 | -0.722067 | 0.810332 | 1.501295 | 1.440865 | -1.367459 | -0.700301 | -1.540662 | 0.159837 | -0.625415 |
HTML 转义
假设你必须在 HTML 中显示 HTML,当渲染器无法区分时可能会有些麻烦。您可以使用escape
格式选项来处理这个问题,甚至可以在包含 HTML 本身的格式化程序中使用它。
[67]:
df4 = pd.DataFrame([['<div></div>', '"&other"', '<span></span>']])
df4.style
[67]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
[68]:
df4.style.format(escape="html")
[68]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
[69]:
df4.style.format('<a href="https://pandas.pydata.org" target="_blank">{}</a>', escape="html")
[69]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
小部件
Styler
与小部件的交互非常好。如果您在线查看而不是自己运行笔记本,您将错过交互调整颜色调色板的功能。
[62]:
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)
)
放大
[63]:
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')])
]
[64]:
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())
[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 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0.23 | 1.03 | -0.84 | -0.59 | -0.96 | -0.22 | -0.62 | 1.84 | -2.05 | 0.87 | -0.92 | -0.23 | 2.15 | -1.33 | 0.08 | -1.25 | 1.20 | -1.05 | 1.06 | -0.42 | 2.29 | -2.59 | 2.82 | 0.68 | -1.58 |
1 | -1.75 | 1.56 | -1.13 | -1.10 | 1.03 | 0.00 | -2.46 | 3.45 | -1.66 | 1.27 | -0.52 | -0.02 | 1.52 | -1.09 | -1.86 | -1.13 | -0.68 | -0.81 | 0.35 | -0.06 | 1.79 | -2.82 | 2.26 | 0.78 | 0.44 |
2 | -0.65 | 3.22 | -1.76 | 0.52 | 2.20 | -0.37 | -3.00 | 3.73 | -1.87 | 2.46 | 0.21 | -0.24 | -0.10 | -0.78 | -3.02 | -0.82 | -0.21 | -0.23 | 0.86 | -0.68 | 1.45 | -4.89 | 3.03 | 1.91 | 0.61 |
3 | -1.62 | 3.71 | -2.31 | 0.43 | 4.17 | -0.43 | -3.86 | 4.16 | -2.15 | 1.08 | 0.12 | 0.60 | -0.89 | 0.27 | -3.67 | -2.71 | -0.31 | -1.59 | 1.35 | -1.83 | 0.91 | -5.80 | 2.81 | 2.11 | 0.28 |
4 | -3.35 | 4.48 | -1.86 | -1.70 | 5.19 | -1.02 | -3.81 | 4.72 | -0.72 | 1.08 | -0.18 | 0.83 | -0.22 | -1.08 | -4.27 | -2.88 | -0.97 | -1.78 | 1.53 | -1.80 | 2.21 | -6.34 | 3.34 | 2.49 | 2.09 |
5 | -0.84 | 4.23 | -1.65 | -2.00 | 5.34 | -0.99 | -4.13 | 3.94 | -1.06 | -0.94 | 1.24 | 0.09 | -1.78 | -0.11 | -4.45 | -0.85 | -2.06 | -1.35 | 0.80 | -1.63 | 1.54 | -6.51 | 2.80 | 2.14 | 3.77 |
6 | -0.74 | 5.35 | -2.11 | -1.13 | 4.20 | -1.85 | -3.20 | 3.76 | -3.22 | -1.23 | 0.34 | 0.57 | -1.82 | 0.54 | -4.43 | -1.83 | -4.03 | -2.62 | -0.20 | -4.68 | 1.93 | -8.46 | 3.34 | 2.52 | 5.81 |
7 | -0.44 | 4.69 | -2.30 | -0.21 | 5.93 | -2.63 | -1.83 | 5.46 | -4.50 | -3.16 | -1.73 | 0.18 | 0.11 | 0.04 | -5.99 | -0.45 | -6.20 | -3.89 | 0.71 | -3.95 | 0.67 | -7.26 | 2.97 | 3.39 | 6.66 |
8 | 0.92 | 5.80 | -3.33 | -0.65 | 5.99 | -3.19 | -1.83 | 5.63 | -3.53 | -1.30 | -1.61 | 0.82 | -2.45 | -0.40 | -6.06 | -0.52 | -6.60 | -3.48 | -0.04 | -4.60 | 0.51 | -5.85 | 3.23 | 2.40 | 5.08 |
9 | 0.38 | 5.54 | -4.49 | -0.80 | 7.05 | -2.64 | -0.44 | 5.35 | -1.96 | -0.33 | -0.80 | 0.26 | -3.37 | -0.82 | -6.05 | -2.61 | -8.45 | -4.45 | 0.41 | -4.71 | 1.89 | -6.93 | 2.14 | 3.00 | 5.16 |
10 | 2.06 | 5.84 | -3.90 | -0.98 | 7.78 | -2.49 | -0.59 | 5.59 | -2.22 | -0.71 | -0.46 | 1.80 | -2.79 | 0.48 | -5.97 | -3.44 | -7.77 | -5.49 | -0.70 | -4.61 | -0.52 | -7.72 | 1.54 | 5.02 | 5.81 |
11 | 1.86 | 4.47 | -2.17 | -1.38 | 5.90 | -0.49 | 0.02 | 5.78 | -1.04 | -0.60 | 0.49 | 1.96 | -1.47 | 1.88 | -5.92 | -4.55 | -8.15 | -3.42 | -2.24 | -4.33 | -1.17 | -7.90 | 1.36 | 5.31 | 5.83 |
12 | 3.19 | 4.22 | -3.06 | -2.27 | 5.93 | -2.64 | 0.33 | 6.72 | -2.84 | -0.20 | 1.89 | 2.63 | -1.53 | 0.75 | -5.27 | -4.53 | -7.57 | -2.85 | -2.17 | -4.78 | -1.13 | -8.99 | 2.11 | 6.42 | 5.60 |
13 | 2.31 | 4.45 | -3.87 | -2.05 | 6.76 | -3.25 | -2.17 | 7.99 | -2.56 | -0.80 | 0.71 | 2.33 | -0.16 | -0.46 | -5.10 | -3.79 | -7.58 | -4.00 | 0.33 | -3.67 | -1.05 | -8.71 | 2.47 | 5.87 | 6.71 |
14 | 3.78 | 4.33 | -3.88 | -1.58 | 6.22 | -3.23 | -1.46 | 5.57 | -2.93 | -0.33 | -0.97 | 1.72 | 3.61 | 0.29 | -4.21 | -4.10 | -6.68 | -4.50 | -2.19 | -2.43 | -1.64 | -9.36 | 3.36 | 6.11 | 7.53 |
15 | 5.64 | 5.31 | -3.98 | -2.26 | 5.91 | -3.30 | -1.03 | 5.68 | -3.06 | -0.33 | -1.16 | 2.19 | 4.20 | 1.01 | -3.22 | -4.31 | -5.74 | -4.44 | -2.30 | -1.36 | -1.20 | -11.27 | 2.59 | 6.69 | 5.91 |
17 | 5.64 | 4.57 | -3.53 | -3.76 | 6.58 | -2.58 | -0.75 | 6.58 | -4.78 | 3.63 | -0.29 | 0.56 | 5.76 | 2.05 | -2.27 | -2.31 | -4.95 | -3.16 | -3.06 | -2.43 | 0.84 | -12.57 | 3.56 | 7.36 | 4.70 |
18 | 5.99 | 5.82 | -2.85 | -4.15 | 7.12 | -3.32 | -1.21 | 7.93 | -4.85 | 1.44 | -0.63 | 0.35 | 7.47 | 0.87 | -1.52 | -2.09 | -4.23 | -2.55 | -2.46 | -2.89 | 1.90 | -9.74 | 3.43 | 7.07 | 4.39 |
19 | 4.03 | 6.23 | -4.10 | -4.11 | 7.19 | -4.10 | -1.52 | 6.53 | -5.21 | -0.24 | 0.01 | 1.16 | 6.43 | -1.97 | -2.64 | -1.66 | -5.20 | -3.25 | -2.87 | -1.65 | 1.64 | -10.66 | 2.83 | 7.48 | 3.94 |
固定表头
如果你在笔记本中显示一个大矩阵或 DataFrame,但希望始终看到列和行标题,可以使用 .set_sticky 方法来操作表格样式的 CSS。
[65]:
bigdf = pd.DataFrame(np.random.randn(16, 100))
bigdf.style.set_sticky(axis="index")
[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 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | -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 |
| 1 | 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 |
| 2 | 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 |
| 3 | -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 |
| 4 | -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 |
| 5 | -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 |
| 6 | 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 |
| 7 | 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 |
| 8 | -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 |
| 9 | -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 |
| 10 | -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 |
| 11 | -0.625210 | 0.288911 | 0.288374 | -1.372667 | -0.591395 | -0.478942 | 1.335664 | -0.459855 | -1.615975 | -1.189676 | 0.374767 | -2.488733 | 0.586656 | -1.422008 | 0.496030 | 1.911128 | -0.560660 | -0.499614 | -0.372171 | -1.833069 | 0.237124 | -0.944446 | 0.912140 | 0.359790 | -1.359235 | 0.166966 | -0.047107 | -0.279789 | -0.594454 | -0.739013 | -1.527645 | 0.401668 | 1.791252 | -2.774848 | 0.523873 | 2.207585 | 0.488999 | -0.339283 | 0.131711 | 0.018409 | 1.186551 | -0.424318 | 1.554994 | -0.205917 | -0.934975 | 0.654102 | -1.227761 | -0.461025 | -0.421201 | -0.058615 | -0.584563 | 0.336913 | -0.477102 | -1.381463 | 0.757745 | -0.268968 | 0.034870 | 1.231686 | 0.236600 | 1.234720 | -0.040247 | 0.029582 | 1.034905 | 0.380204 | -0.012108 | -0.859511 | -0.990340 | -1.205172 | -1.030178 | 0.426676 | 0.497796 | -0.876808 | 0.957963 | 0.173016 | 0.131612 | -1.003556 | -1.069908 | -1.799207 | 1.429598 | -0.116015 | -1.454980 | 0.261917 | 0.444412 | 0.273290 | 0.844115 | 0.218745 | -1.033350 | -1.188295 | 0.058373 | 0.800523 | -1.627068 | 0.861651 | 0.871018 | -0.003733 | -0.243354 | 0.947296 | 0.509406 | 0.044546 | 0.266896 | 1.337165 |
| 12 | 0.699142 | -1.928033 | 0.105363 | 1.042322 | 0.715206 | -0.763783 | 0.098798 | -1.157898 | 0.134105 | 0.042041 | 0.674826 | 0.165649 | -1.622970 | -3.131274 | 0.597649 | -1.880331 | 0.663980 | -0.256033 | -1.524058 | 0.492799 | 0.221163 | 0.429622 | -0.659584 | 1.264506 | -0.032131 | -2.114907 | -0.264043 | 0.457835 | -0.676837 | -0.629003 | 0.489145 | -0.551686 | 0.942622 | -0.512043 | -0.455893 | 0.021244 | -0.178035 | -2.498073 | -0.171292 | 0.323510 | -0.545163 | -0.668909 | -0.150031 | 0.521620 | -0.428980 | 0.676463 | 0.369081 | -0.724832 | 0.793542 | 1.237422 | 0.401275 | 2.141523 | 0.249012 | 0.486755 | -0.163274 | 0.592222 | -0.292600 | -0.547168 | 0.619104 | -0.013605 | 0.776734 | 0.131424 | 1.189480 | -0.666317 | -0.939036 | 1.105515 | 0.621452 | 1.586605 | -0.760970 | 1.649646 | 0.283199 | 1.275812 | -0.452012 | 0.301361 | -0.976951 | -0.268106 | -0.079255 | -1.258332 | 2.216658 | -1.175988 | -0.863497 | -1.653022 | -0.561514 | 0.450753 | 0.417200 | 0.094676 | -2.231054 | 1.316862 | -0.477441 | 0.646654 | -0.200252 | 1.074354 | -0.058176 | 0.120990 | 0.222522 | -0.179507 | 0.421655 | -0.914341 | -0.234178 | 0.741524 |
| 13 | 0.932714 | 1.423761 | -1.280835 | 0.347882 | -0.863171 | -0.852580 | 1.044933 | 2.094536 | 0.806206 | 0.416201 | -1.109503 | 0.145302 | -0.996871 | 0.325456 | -0.605081 | 1.175326 | 1.645054 | 0.293432 | -2.766822 | 1.032849 | 0.079115 | -1.414132 | 1.463376 | 2.335486 | 0.411951 | -0.048543 | 0.159284 | -0.651554 | -1.093128 | 1.568390 | -0.077807 | -2.390779 | -0.842346 | -0.229675 | -0.999072 | -1.367219 | -0.792042 | -1.878575 | 1.451452 | 1.266250 | -0.734315 | 0.266152 | 0.735523 | -0.430860 | 0.229864 | 0.850083 | -2.241241 | 1.063850 | 0.289409 | -0.354360 | 0.113063 | -0.173006 | 1.386998 | 1.886236 | 0.587119 | -0.961133 | 0.399295 | 1.461560 | 0.310823 | 0.280220 | -0.879103 | -1.326348 | 0.003337 | -1.085908 | -0.436723 | 2.111926 | 0.106068 | 0.615597 | 2.152996 | -0.196155 | 0.025747 | -0.039061 | 0.656823 | -0.347105 | 2.513979 | 1.758070 | 1.288473 | -0.739185 | -0.691592 | -0.098728 | -0.276386 | 0.489981 | 0.516278 | -0.838258 | 0.596673 | -0.331053 | 0.521174 | -0.145023 | 0.836693 | -1.092166 | 0.361733 | -1.169981 | 0.046731 | 0.655377 | -0.756852 | 1.285805 | -0.095019 | 0.360253 | 1.370621 | 0.083010 |
| 14 | 0.888893 | 2.288725 | -1.032332 | 0.212273 | -1.091826 | 1.692498 | 1.025367 | 0.550854 | 0.679430 | -1.335712 | -0.798341 | 2.265351 | -1.006938 | 2.059761 | 0.420266 | -1.189657 | 0.506674 | 0.260847 | -0.533145 | 0.727267 | 1.412276 | 1.482106 | -0.996258 | 0.588641 | -0.412642 | -0.920733 | -0.874691 | 0.839002 | 0.501668 | -0.342493 | -0.533806 | -2.146352 | -0.597339 | 0.115726 | 0.850683 | -0.752239 | 0.377263 | -0.561982 | 0.262783 | -0.356676 | -0.367462 | 0.753611 | -1.267414 | -1.330698 | -0.536453 | 0.840938 | -0.763108 | -0.268100 | -0.677424 | 1.606831 | 0.151732 | -2.085701 | 1.219296 | 0.400863 | 0.591165 | -1.485213 | 1.501979 | 1.196569 | -0.214154 | 0.339554 | -0.034446 | 1.176452 | 0.546340 | -1.255630 | -1.309210 | -0.445437 | 0.189437 | -0.737463 | 0.843767 | -0.605632 | -0.060777 | 0.409310 | 1.285569 | -0.622638 | 1.018193 | 0.880680 | 0.046805 | -1.818058 | -0.809829 | 0.875224 | 0.409569 | -0.116621 | -1.238919 | 3.305724 | -0.024121 | -1.756500 | 1.328958 | 0.507593 | -0.866554 | -2.240848 | -0.661376 | -0.671824 | 0.215720 | -0.296326 | 0.481402 | 0.829645 | -0.721025 | 1.263914 | 0.549047 | -1.234945 |
| 15 | -1.978838 | 0.721823 | -0.559067 | -1.235243 | 0.420716 | -0.598845 | 0.359576 | -0.619366 | -1.757772 | -1.156251 | 0.705212 | 0.875071 | -1.020376 | 0.394760 | -0.147970 | 0.230249 | 1.355203 | 1.794488 | 2.678058 | -0.153565 | -0.460959 | -0.098108 | -1.407930 | -2.487702 | 1.823014 | 0.099873 | -0.517603 | -0.509311 | -1.833175 | -0.900906 | 0.459493 | -0.655440 | 1.466122 | -1.531389 | -0.422106 | 0.421422 | 0.578615 | 0.259795 | 0.018941 | -0.168726 | 1.611107 | -1.586550 | -1.384941 | 0.858377 | 1.033242 | 1.701343 | 1.748344 | -0.371182 | -0.843575 | 2.089641 | -0.345430 | -1.740556 | 0.141915 | -2.197138 | 0.689569 | -0.150025 | 0.287456 | 0.654016 | -1.521919 | -0.918008 | -0.587528 | 0.230636 | 0.262637 | 0.615674 | 0.600044 | -0.494699 | -0.743089 | 0.220026 | -0.242207 | 0.528216 | -0.328174 | -1.536517 | -1.476640 | -1.162114 | -1.260222 | 1.106252 | -1.467408 | -0.349341 | -1.841217 | 0.031296 | -0.076475 | -0.353383 | 0.807545 | 0.779064 | -2.398417 | -0.267828 | 1.549734 | 0.814397 | 0.284770 | -0.659369 | 0.761040 | -0.722067 | 0.810332 | 1.501295 | 1.440865 | -1.367459 | -0.700301 | -1.540662 | 0.159837 | -0.625415 |
也可以粘贴多个索引,甚至只有特定级别。
[66]:
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])
[66]:
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 | |||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
A | 0 | 0 | -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 |
1 | 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 |
2 | 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 |
3 | -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 | 0 | -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 | -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 |
2 | 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 |
3 | 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 |
B | 0 | 0 | -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 |
1 | -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 |
2 | -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 |
3 | -0.625210 | 0.288911 | 0.288374 | -1.372667 | -0.591395 | -0.478942 | 1.335664 | -0.459855 | -1.615975 | -1.189676 | 0.374767 | -2.488733 | 0.586656 | -1.422008 | 0.496030 | 1.911128 | -0.560660 | -0.499614 | -0.372171 | -1.833069 | 0.237124 | -0.944446 | 0.912140 | 0.359790 | -1.359235 | 0.166966 | -0.047107 | -0.279789 | -0.594454 | -0.739013 | -1.527645 | 0.401668 | 1.791252 | -2.774848 | 0.523873 | 2.207585 | 0.488999 | -0.339283 | 0.131711 | 0.018409 | 1.186551 | -0.424318 | 1.554994 | -0.205917 | -0.934975 | 0.654102 | -1.227761 | -0.461025 | -0.421201 | -0.058615 | -0.584563 | 0.336913 | -0.477102 | -1.381463 | 0.757745 | -0.268968 | 0.034870 | 1.231686 | 0.236600 | 1.234720 | -0.040247 | 0.029582 | 1.034905 | 0.380204 | -0.012108 | -0.859511 | -0.990340 | -1.205172 | -1.030178 | 0.426676 | 0.497796 | -0.876808 | 0.957963 | 0.173016 | 0.131612 | -1.003556 | -1.069908 | -1.799207 | 1.429598 | -0.116015 | -1.454980 | 0.261917 | 0.444412 | 0.273290 | 0.844115 | 0.218745 | -1.033350 | -1.188295 | 0.058373 | 0.800523 | -1.627068 | 0.861651 | 0.871018 | -0.003733 | -0.243354 | 0.947296 | 0.509406 | 0.044546 | 0.266896 |
1 | 0 | 0.699142 | -1.928033 | 0.105363 | 1.042322 | 0.715206 | -0.763783 | 0.098798 | -1.157898 | 0.134105 | 0.042041 | 0.674826 | 0.165649 | -1.622970 | -3.131274 | 0.597649 | -1.880331 | 0.663980 | -0.256033 | -1.524058 | 0.492799 | 0.221163 | 0.429622 | -0.659584 | 1.264506 | -0.032131 | -2.114907 | -0.264043 | 0.457835 | -0.676837 | -0.629003 | 0.489145 | -0.551686 | 0.942622 | -0.512043 | -0.455893 | 0.021244 | -0.178035 | -2.498073 | -0.171292 | 0.323510 | -0.545163 | -0.668909 | -0.150031 | 0.521620 | -0.428980 | 0.676463 | 0.369081 | -0.724832 | 0.793542 | 1.237422 | 0.401275 | 2.141523 | 0.249012 | 0.486755 | -0.163274 | 0.592222 | -0.292600 | -0.547168 | 0.619104 | -0.013605 | 0.776734 | 0.131424 | 1.189480 | -0.666317 | -0.939036 | 1.105515 | 0.621452 | 1.586605 | -0.760970 | 1.649646 | 0.283199 | 1.275812 | -0.452012 | 0.301361 | -0.976951 | -0.268106 | -0.079255 | -1.258332 | 2.216658 | -1.175988 | -0.863497 | -1.653022 | -0.561514 | 0.450753 | 0.417200 | 0.094676 | -2.231054 | 1.316862 | -0.477441 | 0.646654 | -0.200252 | 1.074354 | -0.058176 | 0.120990 | 0.222522 | -0.179507 | 0.421655 | -0.914341 |
1 | 0.932714 | 1.423761 | -1.280835 | 0.347882 | -0.863171 | -0.852580 | 1.044933 | 2.094536 | 0.806206 | 0.416201 | -1.109503 | 0.145302 | -0.996871 | 0.325456 | -0.605081 | 1.175326 | 1.645054 | 0.293432 | -2.766822 | 1.032849 | 0.079115 | -1.414132 | 1.463376 | 2.335486 | 0.411951 | -0.048543 | 0.159284 | -0.651554 | -1.093128 | 1.568390 | -0.077807 | -2.390779 | -0.842346 | -0.229675 | -0.999072 | -1.367219 | -0.792042 | -1.878575 | 1.451452 | 1.266250 | -0.734315 | 0.266152 | 0.735523 | -0.430860 | 0.229864 | 0.850083 | -2.241241 | 1.063850 | 0.289409 | -0.354360 | 0.113063 | -0.173006 | 1.386998 | 1.886236 | 0.587119 | -0.961133 | 0.399295 | 1.461560 | 0.310823 | 0.280220 | -0.879103 | -1.326348 | 0.003337 | -1.085908 | -0.436723 | 2.111926 | 0.106068 | 0.615597 | 2.152996 | -0.196155 | 0.025747 | -0.039061 | 0.656823 | -0.347105 | 2.513979 | 1.758070 | 1.288473 | -0.739185 | -0.691592 | -0.098728 | -0.276386 | 0.489981 | 0.516278 | -0.838258 | 0.596673 | -0.331053 | 0.521174 | -0.145023 | 0.836693 | -1.092166 | 0.361733 | -1.169981 | 0.046731 | 0.655377 | -0.756852 | 1.285805 | -0.095019 | 0.360253 | 1.370621 |
2 | 0.888893 | 2.288725 | -1.032332 | 0.212273 | -1.091826 | 1.692498 | 1.025367 | 0.550854 | 0.679430 | -1.335712 | -0.798341 | 2.265351 | -1.006938 | 2.059761 | 0.420266 | -1.189657 | 0.506674 | 0.260847 | -0.533145 | 0.727267 | 1.412276 | 1.482106 | -0.996258 | 0.588641 | -0.412642 | -0.920733 | -0.874691 | 0.839002 | 0.501668 | -0.342493 | -0.533806 | -2.146352 | -0.597339 | 0.115726 | 0.850683 | -0.752239 | 0.377263 | -0.561982 | 0.262783 | -0.356676 | -0.367462 | 0.753611 | -1.267414 | -1.330698 | -0.536453 | 0.840938 | -0.763108 | -0.268100 | -0.677424 | 1.606831 | 0.151732 | -2.085701 | 1.219296 | 0.400863 | 0.591165 | -1.485213 | 1.501979 | 1.196569 | -0.214154 | 0.339554 | -0.034446 | 1.176452 | 0.546340 | -1.255630 | -1.309210 | -0.445437 | 0.189437 | -0.737463 | 0.843767 | -0.605632 | -0.060777 | 0.409310 | 1.285569 | -0.622638 | 1.018193 | 0.880680 | 0.046805 | -1.818058 | -0.809829 | 0.875224 | 0.409569 | -0.116621 | -1.238919 | 3.305724 | -0.024121 | -1.756500 | 1.328958 | 0.507593 | -0.866554 | -2.240848 | -0.661376 | -0.671824 | 0.215720 | -0.296326 | 0.481402 | 0.829645 | -0.721025 | 1.263914 | 0.549047 |
3 | -1.978838 | 0.721823 | -0.559067 | -1.235243 | 0.420716 | -0.598845 | 0.359576 | -0.619366 | -1.757772 | -1.156251 | 0.705212 | 0.875071 | -1.020376 | 0.394760 | -0.147970 | 0.230249 | 1.355203 | 1.794488 | 2.678058 | -0.153565 | -0.460959 | -0.098108 | -1.407930 | -2.487702 | 1.823014 | 0.099873 | -0.517603 | -0.509311 | -1.833175 | -0.900906 | 0.459493 | -0.655440 | 1.466122 | -1.531389 | -0.422106 | 0.421422 | 0.578615 | 0.259795 | 0.018941 | -0.168726 | 1.611107 | -1.586550 | -1.384941 | 0.858377 | 1.033242 | 1.701343 | 1.748344 | -0.371182 | -0.843575 | 2.089641 | -0.345430 | -1.740556 | 0.141915 | -2.197138 | 0.689569 | -0.150025 | 0.287456 | 0.654016 | -1.521919 | -0.918008 | -0.587528 | 0.230636 | 0.262637 | 0.615674 | 0.600044 | -0.494699 | -0.743089 | 0.220026 | -0.242207 | 0.528216 | -0.328174 | -1.536517 | -1.476640 | -1.162114 | -1.260222 | 1.106252 | -1.467408 | -0.349341 | -1.841217 | 0.031296 | -0.076475 | -0.353383 | 0.807545 | 0.779064 | -2.398417 | -0.267828 | 1.549734 | 0.814397 | 0.284770 | -0.659369 | 0.761040 | -0.722067 | 0.810332 | 1.501295 | 1.440865 | -1.367459 | -0.700301 | -1.540662 | 0.159837 |
HTML 转义
假设您必须在 HTML 中显示 HTML,当渲染器无法区分时可能会有些麻烦。您可以使用escape
格式选项来处理这个问题,甚至可以在包含 HTML 本身的格式化程序中使用它。
[67]:
df4 = pd.DataFrame([['<div></div>', '"&other"', '<span></span>']])
df4.style
[67]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
[68]:
df4.style.format(escape="html")
[68]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
[69]:
df4.style.format('<a href="https://pandas.pydata.org" target="_blank">{}</a>', escape="html")
[69]:
0 | 1 | 2 | |
---|---|---|---|
0 | "&other" |
导出到 Excel
从版本 0.20.0 开始,可以使用 OpenPyXL
或 XlsxWriter
引擎将带有样式的 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-style
和border-left-style
),以及所有边的border
简写(border: 1px solid green
)或指定边(border-left: 1px solid green
)。使用border
简写将覆盖之前设置的任何边框属性(有关更多详细信息,请参阅 CSS Working Group) -
目前仅支持 CSS2 命名颜色和形式为
#rgb
或#rrggbb
的十六进制颜色。 -
以下伪 CSS 属性也可用于设置 Excel 特定的样式属性:
-
number-format
-
border-style
(用于 Excel 特定样式的“hair”、“mediumDashDot”、“dashDotDot”、“mediumDashDotDot”、“dashDot”、“slantDashDot”或“mediumDashed”)
-
表级样式和数据单元格 CSS 类不包括在导出到 Excel 中:单个单元格必须通过 Styler.apply
和/或 Styler.map
方法映射其属性。
[70]:
df2.style.\
map(style_negative, props='color:red;').\
highlight_max(axis=0).\
to_excel('styled.xlsx', engine='openpyxl')
输出的屏幕截图:
导出到 LaTeX
从版本 1.3.0 开始,支持将 Styler
导出到 LaTeX。有关 .to_latex 方法的文档提供了更多详细信息和大量示例。
关于 CSS 和 HTML 的更多信息
层叠样式表(CSS)语言旨在影响浏览器如何呈现 HTML 元素,具有其自己的特点。它从不报告错误:它只是默默地忽略它们,不会按照您的意图呈现对象,因此有时可能令人沮丧。以下是关于 Styler
如何创建 HTML 并与 CSS 交互的简要介绍,以及避免常见陷阱的建议。
CSS 类和 Ids
每个单元格附加的 CSS class
的精确结构如下。
-
具有索引和列名称的单元格包括
index_name
和level<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_trim
或row_trim
id
的结构是T_uuid_level<k>_row<m>_col<n>
,其中level<k>
仅用于标题,标题只会有row<m>
或col<n>
中的一个,取决于需要哪个。默认情况下,我们还为每个 DataFrame 的每行/列标识符添加了一个 UUID,以便一个 DataFrame 的样式不会与同一笔记本或页面中另一个 DataFrame 的样式发生冲突。您可以在优化中阅读更多关于 UUID 使用的信息。
我们可以通过调用.to_html()方法来查看 HTML 的示例。
[71]:
print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.to_html())
<style type="text/css">
</style>
<table id="T_a1de3">
<thead>
<tr>
<th class="blank level0" > </th>
<th id="T_a1de3_level0_col0" class="col_heading level0 col0" >c1</th>
<th id="T_a1de3_level0_col1" class="col_heading level0 col1" >c2</th>
</tr>
</thead>
<tbody>
<tr>
<th id="T_a1de3_level0_row0" class="row_heading level0 row0" >i1</th>
<td id="T_a1de3_row0_col0" class="data row0 col0" >1</td>
<td id="T_a1de3_row0_col1" class="data row0 col1" >2</td>
</tr>
<tr>
<th id="T_a1de3_level0_row1" class="row_heading level0 row1" >i2</th>
<td id="T_a1de3_row1_col0" class="data row1 col0" >3</td>
<td id="T_a1de3_row1_col1" class="data row1 col1" >4</td>
</tr>
</tbody>
</table>
CSS 层次结构
示例已经表明,当 CSS 样式重叠时,出现在 HTML 渲染中的最后一个将具有优先权。因此,以下会产生不同的结果:
[72]:
df4 = pd.DataFrame([['text']])
df4.style.map(lambda x: 'color:green;')\
.map(lambda x: 'color:red;')
[72]:
0 | |
---|---|
0 | text |
[73]:
df4.style.map(lambda x: 'color:red;')\
.map(lambda x: 'color:green;')
[73]:
0 | |
---|---|
0 | text |
这仅适用于层次结构或重要性相等的 CSS 规则。您可以在这里阅读更多关于 CSS 特异性的信息,但对于我们的目的,总结关键点就足够了:
每个 HTML 元素的 CSS 重要性分数是从零开始,然后逐渐增加:
-
1000 用于内联样式属性
-
每个 ID 的 100
-
每个属性、类或伪类的 10 个
-
每个元素名称或伪元素的 1
让我们用这个来描述以下配置的操作
[74]:
df4.style.set_uuid('a_')\
.set_table_styles([{'selector': 'td', 'props': 'color:red;'}])\
.map(lambda x: 'color:green;')
[74]:
0 | |
---|---|
0 | text |
这段文字是红色的,因为生成的选择器#T_a_ td
价值为 101(ID 加元素),而#T_a_row0_col0
只值 100(ID),因此被认为是次要的,即使在 HTML 中它出现在前一个之后。
[75]:
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']]))
[75]:
0 | |
---|---|
0 | text |
在上述情况下,文本是蓝色的,因为选择器#T_b_ .cls-1
价值为 110(ID 加类),具有优先权。
[76]:
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']]))
[76]:
0 | |
---|---|
0 | text |
现在我们创建了另一个表格样式,这次选择器T_c_ td.data
(ID 加元素加类)被提升到 111。
如果您的样式未能应用,并且真的很令人沮丧,请尝试!important
王牌。
[77]:
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']]))
[77]:
0 | |
---|---|
0 | text |
最终终于得到了那个绿色的文本!
CSS 类和 ID
附加到每个单元格的 CSS class
的精确结构如下。
-
包含索引和列名的单元格包括
index_name
和level<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_trim
或row_trim
id
的结构是T_uuid_level<k>_row<m>_col<n>
,其中level<k>
仅用于标题,标题只会有row<m>
或col<n>
中的一个,取决于需要哪个。默认情况下,我们还为每个 DataFrame 的每行/列标识符添加了一个 UUID,以确保同一笔记本或页面中的一个 DataFrame 的样式不会与另一个 DataFrame 的样式发生冲突。您可以在优化中了解有关 UUID 使用的更多信息。
我们可以通过调用.to_html()方法来查看 HTML 的示例。
[71]:
print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.to_html())
<style type="text/css">
</style>
<table id="T_a1de3">
<thead>
<tr>
<th class="blank level0" > </th>
<th id="T_a1de3_level0_col0" class="col_heading level0 col0" >c1</th>
<th id="T_a1de3_level0_col1" class="col_heading level0 col1" >c2</th>
</tr>
</thead>
<tbody>
<tr>
<th id="T_a1de3_level0_row0" class="row_heading level0 row0" >i1</th>
<td id="T_a1de3_row0_col0" class="data row0 col0" >1</td>
<td id="T_a1de3_row0_col1" class="data row0 col1" >2</td>
</tr>
<tr>
<th id="T_a1de3_level0_row1" class="row_heading level0 row1" >i2</th>
<td id="T_a1de3_row1_col0" class="data row1 col0" >3</td>
<td id="T_a1de3_row1_col1" class="data row1 col1" >4</td>
</tr>
</tbody>
</table>
CSS 层次结构
示例��经表明,当 CSS 样式重叠时,HTML 渲染中排在后面的样式优先。因此,以下会产生不同的结果:
[72]:
df4 = pd.DataFrame([['text']])
df4.style.map(lambda x: 'color:green;')\
.map(lambda x: 'color:red;')
[72]:
0 | |
---|---|
0 | 文本 |
[73]:
df4.style.map(lambda x: 'color:red;')\
.map(lambda x: 'color:green;')
[73]:
0 | |
---|---|
0 | 文本 |
这仅适用于层次结构或重要性相等的 CSS 规则。您可以在这里了解更多关于 CSS 特异性的信息,但对于我们的目的,总结关键点就足够了:
对每个 HTML 元素的 CSS 重要性得分是从零开始,然后逐步添加:
-
内联样式属性 1000
-
每个 ID100
-
每个属性、类或伪类 10
-
每个元素名称或伪元素 1
让我们使用这个来描述以下配置的操作
[74]:
df4.style.set_uuid('a_')\
.set_table_styles([{'selector': 'td', 'props': 'color:red;'}])\
.map(lambda x: 'color:green;')
[74]:
0 | |
---|---|
0 | 文本 |
这段文字是红色的,因为生成的选择器#T_a_ td
价值为 101(ID 加元素),而#T_a_row0_col0
只值 100(ID),因此被认为是次要的,即使在 HTML 中它出现在前一个之后。
[75]:
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']]))
[75]:
0 | |
---|---|
0 | 文本 |
在上述情况下,文字是蓝色的,因为选择器#T_b_ .cls-1
价值为 110(ID 加类),具有优先权。
[76]:
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']]))
[76]:
0 | |
---|---|
0 | 文本 |
现在我们创建了另一种表格样式,这次选择器T_c_ td.data
(ID 加元素加类)被提升到了 111。
如果您的样式未能应用,这真的很令人沮丧,请尝试使用!important
王牌。
[77]:
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']]))
[77]:
0 | |
---|---|
0 | 文本 |
终于得到了那个绿色的文字!
可扩展性
pandas 的核心是,并将始终是“高性能、易于使用的数据结构”。考虑到这一点,我们希望DataFrame.style
实现两个目标
-
提供一个令人愉快的交互式使用 API,并且对于许多任务来说“足够好”
-
为专用库提供基础
如果您在此基础上构建了一个很棒的库,请告诉我们,我们将链接到它。
子类化
如果默认模板不完全符合您的需求,您可以子类化Styler
并扩展或覆盖模板。我们将展示一个扩展默认模板以在每个表格之前插入自定义标题的示例。
[78]:
from jinja2 import Environment, ChoiceLoader, FileSystemLoader
from IPython.display import HTML
from pandas.io.formats.style import Styler
我们将使用以下模板:
[79]:
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
子类。
[80]:
class MyStyler(Styler):
env = Environment(
loader=ChoiceLoader([
FileSystemLoader("templates"), # contains ours
Styler.loader, # the default
])
)
template_html_table = env.get_template("myhtml.tpl")
请注意,我们在环境的加载器中包含了原始加载器。这是因为我们扩展了原始模板,所以 Jinja 环境需要能够找到它。
现在我们可以使用自定义的样式。它的__init__
接受一个 DataFrame。
[81]:
MyStyler(df3)
[81]:
我的表格
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
方法中提供值。
[82]:
HTML(MyStyler(df3).to_html(table_title="Extending Example"))
[82]:
扩展示例
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
方法,它与自定义子类相同。
[83]:
EasyStyler = Styler.from_custom_template("templates", "myhtml.tpl")
HTML(EasyStyler(df3).to_html(table_title="Another Title"))
[83]:
另一个标题
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 |
模板结构
这是样式生成模板和表格生成模板的模板结构:
样式模板:
[85]:
HTML(style_structure)
[85]:
before_stylestyle
<style type="text/css">
表格样式 before_cellstylecellstyle
</style>
表格模板:
[87]:
HTML(table_structure)
[87]:
before_tabletable
<table ...>
captiontheadbefore_head_rowshead_tr(循环遍历标题)after_head_rowstbodybefore_rowstr(循环遍历数据行)after_rows
</table>
after_table
查看Github 存储库中的模板以获取更多详细信息。
子类化
如果默认模板不完全符合您的需求,您可以子类化Styler
并扩展或覆盖模板。我们将展示一个示例,扩展默认模板以在每个表格之前插入自定义标题。
[78]:
from jinja2 import Environment, ChoiceLoader, FileSystemLoader
from IPython.display import HTML
from pandas.io.formats.style import Styler
我们将使用以下模板:
[79]:
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
的子类,让它知道这个模板。
[80]:
class MyStyler(Styler):
env = Environment(
loader=ChoiceLoader([
FileSystemLoader("templates"), # contains ours
Styler.loader, # the default
])
)
template_html_table = env.get_template("myhtml.tpl")
请注意,我们在环境的加载器中包含了原始加载器。这是因为我们扩展了原始模板,所以 Jinja 环境需要能够找到它。
现在我们可以使用自定义的样式。它的__init__
接受一个 DataFrame。
[81]:
MyStyler(df3)
[81]:
我的表格
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
方法中提供值。
[82]:
HTML(MyStyler(df3).to_html(table_title="Extending Example"))
[82]:
扩展示例
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
方法,其功能与自定义子类相同。
[83]:
EasyStyler = Styler.from_custom_template("templates", "myhtml.tpl")
HTML(EasyStyler(df3).to_html(table_title="Another Title"))
[83]:
另一个标题
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 |
模板结构
这是样式生成模板和表格生成模板的模板结构:
样式模板:
[85]:
HTML(style_structure)
[85]:
before_stylestyle
<style type="text/css">
table_stylesbefore_cellstylecellstyle
</style>
表格模板:
[87]:
HTML(table_structure)
[87]:
before_tabletable
<table ...>
captiontheadbefore_head_rowshead_tr (循环遍历标题)after_head_rowstbodybefore_rowstr (循环遍历数据行)after_rows
</table>
after_table
查看更多详细信息,请参考GitHub 仓库中的模板。
模板结构
这是样式生成模板和表格生成模板的模板结构:
样式模板:
[85]:
HTML(style_structure)
[85]:
before_stylestyle
<style type="text/css">
table_stylesbefore_cellstylecellstyle
</style>
表格模板:
[87]:
HTML(table_structure)
[87]:
before_tabletable
<table ...>
captiontheadbefore_head_rowshead_tr (循环遍历标题)after_head_rowstbodybefore_rowstr (循环遍历数据行)after_rows
</table>
after_table
查看更多详细信息,请参考GitHub 仓库中的模板。