突出显示列中最大的值

2024-05-17 11:13:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我用黄色突出显示了我的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')

Tags: 代码inforreturnifisdefelse
1条回答
网友
1楼 · 发布于 2024-05-17 11:13:54

您可以尝试:

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

相关问题 更多 >