代码之家  ›  专栏  ›  技术社区  ›  bismo

如何在pandas中设置特定MultiIndex值行中所有单元格的样式

  •  0
  • bismo  · 技术社区  · 1 年前

    设置

    我有以下几点 df :

    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)
    
    

    我想做什么

    我正在努力设计风格 df 以便每个细胞 count == 'total' 被加粗了。

    我试过的

    我能够索引所有行 计数==“总计” 使用以下代码:

    idx = pd.IndexSlice
    totals = df.loc[idx[:, 'total'],:]
    

    但当我尝试应用一个函数时:

    def df_style(val):
        return "font-weight: bold"
    
    df.style.applymap(df_style,subset=totals)
    
    

    我得到以下错误:

    KeyError: 0
    

    我该如何设计这个风格 df 以便所有细胞 计数==“总计” 是粗体吗?

    Here is a similar question 尽管只有一个常规索引而不是MultiIndex。

    1 回复  |  直到 1 年前
        1
  •  1
  •   ouroboros1    1 年前

    这里有一种方法:

    # used `np.random.seed(0)` for reproducibility
    
    def highlight_total(s):
        m = s.index.get_level_values('count') == 'total'
        return np.where(m, 'font-weight: bold', None)
        
    df.style.apply(highlight_total)
    

    输出:

    df with total rows in bold

    解释


    具体来说,穿越 df 按行排列 ,你可以这样做:

    def highlight_total(s):
        return ['font-weight: bold']*len(s) if s.name[1] == 'total' else [None]*len(s)
        
    df.style.apply(highlight_total, axis=1)
    

    所以,我们在这里访问 s.name[1] ,名称理解为 ('fruit', 'total') , ('vegetable', 'total') 等等。导致相同的结果。