pandas.io.formats.style.Styler.relabel_index#

Styler.relabel_index(labels, axis=0, level=None)[源代码]#

重命名索引或列标题的键,以显示一组指定的值。

在 1.5.0 版本加入.

Parameters:
labelslist-like 或 Index

要显示的新标签。必须与未隐藏的底层值的长度相同。

axis{“index”, 0, “columns”, 1}

应用于索引或列。

levelint, str, list, optional

应用新标签的级别。如果为 None,则应用于未隐藏的 Index 或 MultiIndex 的所有级别。

Returns:
Styler

参见

Styler.format_index

格式化索引或列标题的文本显示值。

Styler.hide

隐藏索引、列标题或指定数据以供显示。

Notes

作为 Styler 的一部分,此方法允许完全由用户指定索引的显示,而不影响底层的 DataFrame 数据、索引或列标题。这意味着索引的灵活性得以保持,而最终的显示是可以自定义的。

由于 Styler 被设计为通过方法链进行渐进式构建,因此此方法会根据**当前指定的隐藏元素**进行响应。这很有用,因为这意味着如果索引或列标题的大部分已被隐藏,则不必指定所有新标签。以下示例产生等效的显示(注意每种情况下的 labels 长度)。

# relabel first, then hide
df = pd.DataFrame({"col": ["a", "b", "c"]})
df.style.relabel_index(["A", "B", "C"]).hide([0,1])
# hide first, then relabel
df = pd.DataFrame({"col": ["a", "b", "c"]})
df.style.hide([0,1]).relabel_index(["C"])

此方法应在以下任一情况下使用,而不是使用 Styler.format_index() (请参阅示例):

  • 需要一组由底层索引键决定的特定标签。

  • 底层索引键的函数需要一个计数器变量,例如在枚举时可用的变量。

Examples

基本用法

>>> df = pd.DataFrame({"col": ["a", "b", "c"]})
>>> df.style.relabel_index(["A", "B", "C"])  
     col
A      a
B      b
C      c

与预隐藏元素的链接

>>> df.style.hide([0,1]).relabel_index(["C"])  
     col
C      c

使用 MultiIndex

>>> midx = pd.MultiIndex.from_product([[0, 1], [0, 1], [0, 1]])
>>> df = pd.DataFrame({"col": list(range(8))}, index=midx)
>>> styler = df.style  
          col
0  0  0     0
      1     1
   1  0     2
      1     3
1  0  0     4
      1     5
   1  0     6
      1     7
>>> styler.hide((midx.get_level_values(0)==0)|(midx.get_level_values(1)==0))
...  
>>> styler.hide(level=[0,1])  
>>> styler.relabel_index(["binary6", "binary7"])  
          col
binary6     6
binary7     7

我们也可以通过先索引再重新标记来实现上述效果

>>> styler = df.loc[[(1,1,0), (1,1,1)]].style
>>> styler.hide(level=[0,1]).relabel_index(["binary6", "binary7"])
...  
          col
binary6     6
binary7     7

定义一个使用枚举计数器的格式化函数。另请注意,在这种情况下,索引键的值会作为字符串标签传递,因此也可以使用花括号(如果字符串已预先格式化,则使用双花括号)将其插入标签中,

>>> df = pd.DataFrame({"samples": np.random.rand(10)})
>>> styler = df.loc[np.random.randint(0,10,3)].style
>>> styler.relabel_index([f"sample{i+1} ({{}})" for i in range(3)])
...  
                 samples
sample1 (5)     0.315811
sample2 (0)     0.495941
sample3 (2)     0.067946