Python 高亮显示数据集中列的最大值
我用黄色突出显示了我的df的最大值,代码如下:Python 高亮显示数据集中列的最大值,python,pandas,highlight,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 =
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')
您可以尝试:
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)
输出: