pandas 1.3.5中有几个选项,尽管这是一个不需要使用1.4.0中可用的hide
函数的简单操作.
Removing Index Levels >= 1
由于在多索引中使用了行跨度,nth-child
在此不起作用.但是,我们可以利用样式器添加的默认CSS类:
因此,我们可以简单地排除CSS Select 器.level2:not(.col_heading)
,其中n
是我们想要隐藏的任何级别(level0需要稍微修改).我们需要排除col\u标题,以便不删除任何列标题.
此外,我们还需要删除blank
个级别中的一个,以便顶层对齐.我采取了简单的方法,并 Select 删除每行的第一个空格.
Note: This is not a durable solution and will be impacted by structure changes like MultiIndex columns.
下面是一个使用样式隐藏level 2的示例
hide_column_styles = [
{
# Remove all row values associated with level2
'selector': f'th.level2:not(.col_heading)',
'props': [('display', 'none')]
},
{
# Remove the first th in each row if it is .blank
'selector': 'thead th:first-child.blank',
'props': [('display', 'none')]
}
]
# Basic border
border_styles = [{
'selector': '',
'props': [('border-collapse', 'collapse')]
}, {
'selector': 'table, th, td',
'props': [('border', '1px solid black')]
}]
(
data.reset_index()
.set_index(["Ex Date", "Portfolio", "index"])
.style
.apply(multi_highlighter, range_colors=range_colors, axis=1)
.set_table_styles([*hide_column_styles, *border_styles])
)
正在删除索引级别0
如果试图删除level0,我们只需要隐藏level0:
hide_column_styles = [
{
# Remove all values associated with level0 (including the first header row)
'selector': f'th.level0:not(.col_heading)',
'props': [('display', 'none')]
}
]
第一个索引列将具有类.level0和隐藏,无需额外的 Select 器:
<tr>
<th class="blank"> </th>
<th class="blank"> </th>
<th class="blank level0"> </th> <!-- This will match and be hidden -->
<th class="col_heading level0 col0">Position</th>
<th class="col_heading level0 col1">Strike</th>
</tr>
隐藏不影响多索引唯一性的级别
如果删除级别后索引级别将保持唯一,则只需删除droplevel即可删除索引before创建样式器:
例如,下面是通过删除级别0来删除级别0的示例.
n = 0 # level to drop
(
data
.reset_index()
.set_index(["Ex Date", "Portfolio", "index"])
.droplevel(level=n) # Drop level from DataFrame
.style
.apply(multi_highlighter, range_colors=range_colors, axis=1)
.set_table_styles([
{
'selector': 'table, th, td',
'props': [('border', '1px solid black')]
}
])
)
注意:只有当多重索引是唯一的after级别被删除时,这才有效
如果某个级别被删除,导致非唯一的多索引(如级别2),则在使用Styler.apply
或Styler.applymap
时会出现关键错误:
KeyError:"Styler.apply
和.applymap
与非唯一索引或列不兼容."
Pandas 1.4.0及更新版本
为了让这个问题的future 读者非常清楚,这是1.4.0之前版本的一个变通方法.使用hide函数更简单,解决方案比CSS Select 器更耐用:
n = 2 # level to drop
border_styles = [{
'selector': '',
'props': [('border-collapse', 'collapse')]
}, {
'selector': 'table, th, td',
'props': [('border', '1px solid black')]
}]
(
data
.reset_index()
.set_index(["Ex Date", "Portfolio", "index"])
.style
.apply(multi_highlighter, range_colors=range_colors, axis=1)
.hide(axis=0, level=n)
.set_table_styles(border_styles)
)