【问题标题】:Highlighting nlargest values of columns in a pandas df突出显示pandas df中列的最大值
【发布时间】:2019-12-12 09:33:01
【问题描述】:

我使用以下代码突出显示了我的 df 的黄色最大值:

def highlight_max(s):
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

pivot_p.style.apply(highlight_max)

但现在我想突出显示每列的 5 个最大值。我已经尝试了以下代码,但它不起作用:

def highlight_large(s):
    is_large = s == s.nlargest(5)
    return ['background-color: yellow' if v else '' for v in is_large]

pivot_p.style.apply(highlight_large)

错误:

ValueError: ('Can only compare identically-labeled Series objects', 'occurred at index %_0')

【问题讨论】:

    标签: python pandas highlight


    【解决方案1】:

    你可以试试:

    def highlight_max(s):
        is_large = s.nlargest(5).values
        return ['background-color: yellow' if v in is_large else '' for v in s]
    

    完整示例:

    # Import modules
    import pandas as pd
    import numpy as np
    
    # Create example dataframe
    pivot_p = pd.DataFrame({"a": np.random.randint(0,15,20),
                      "b": np.random.random(20)})
    
    def highlight_max(s):
        # Get 5 largest values of the column
        is_large = s.nlargest(5).values
        # Apply style is the current value is among the 5 biggest values
        return ['background-color: yellow' if v in is_large else '' for v in s]
    
    pivot_p.style.apply(highlight_max)
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-05
      • 2021-10-04
      • 1970-01-01
      • 2021-07-11
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多