如何为Pandas中MultiIndex的count层级为'total'的整行单元格设置加粗样式
如何为Pandas中MultiIndex的count层级为'total'的整行单元格设置加粗样式
问题背景
先确认下你的数据结构,是通过以下代码生成的带MultiIndex的DataFrame:
import pandas as pd import numpy as np arrays = [ np.array(["fruit", "fruit", "fruit","vegetable", "vegetable", "vegetable"]), np.array(["one", "two", "total", "one", "two", "total"]), ] df = pd.DataFrame(np.random.randn(6, 4), index=arrays) df.index.set_names(['item','count'],inplace=True)
你的需求很明确:把所有count层级为'total'的行的所有单元格设置为加粗样式。
你之前尝试的问题所在
你用IndexSlice选中目标行的逻辑是对的,但在style.applymap里犯了个小错误——把筛选后的DataFrame(totals)传给了subset参数。实际上subset需要的是索引定位器(比如IndexSlice对象),而不是已经筛选好的DataFrame,这才导致了KeyError: 0的报错。
正确的解决方法
这里有两种简单可行的实现方式:
方法1:直接用IndexSlice作为subset参数
这是最简洁的方式,直接在applymap的subset里指定count为'total'的所有行:
def df_style(val): return "font-weight: bold" idx = pd.IndexSlice # 直接用IndexSlice定位目标行,作为subset传入 styled_df = df.style.applymap(df_style, subset=idx[:, 'total']) # 查看样式后的结果 styled_df
方法2:按行判断索引设置样式
如果后续需要添加更复杂的样式逻辑,也可以用apply按行处理,通过行的MultiIndex来判断:
def bold_total_row(row): # row.name是当前行的MultiIndex,取第二个层级(count)做判断 if row.name[1] == 'total': # 对该行所有单元格返回加粗样式 return ['font-weight: bold'] * len(row) else: # 其他行返回空样式 return [''] * len(row) # axis=1表示按行应用样式函数 styled_df = df.style.apply(bold_total_row, axis=1) styled_df
这两种方法都能正确实现需求,不会再出现之前的报错。
备注:内容来源于stack exchange,提问作者bismo
相关产品推荐
相关产品推荐

