突出显示熊猫df中列的最大值

时间:2019-08-04 17:29:19

标签: python pandas highlight

我用以下代码突出显示了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')

1 个答案:

答案 0 :(得分: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)

输出:

enter image description here