📜  在 Pandas 中突出显示每列中的最大值

📅  最后修改于: 2022-05-13 01:54:59.983000             🧑  作者: Mango

在 Pandas 中突出显示每列中的最大值

让我们讨论如何突出显示 Pandas Dataframe 中的最大值。让我们首先制作一个数据框:

例子:

Python3
# Import Required Libraries
import pandas as pd
import numpy as np
  
# Create a dictionary for the dataframe
dict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel',
                 'Sanskriti', 'Abhishek Jain'], 
        'Age': [22, 20, 45, 21, 22],
        'Marks': [90, 84, 33, 87, 82]}
  
# Converting Dictionary to Pandas Dataframe
df = pd.DataFrame(dict)
  
# Print Dataframe
df


Python3
# Highlighting the maximum values of
# last 2 columns
df.style.highlight_max(color = 'lightgreen', axis = 0)


Python3
# Defining custom function which returns 
# the list for df.style.apply() method
def highlight_max(s):
    is_max = s == s.max()
    return ['color: green' if cell else '' for cell in is_max]
  
df.style.apply(highlight_max)


Python3
# Defining custom function which returns 
# the list for df.style.apply() method
def highlight_max(s):
    is_max = s == s.max()
    return ['background: lightgreen' if cell else '' for cell in is_max]
  
df.style.apply(highlight_max)


Python3
# Defining custom function which returns
# the list for df.style.apply() method
def highlight_max(s):
    if s.dtype == np.object:
        is_max = [False for _ in range(s.shape[0])]
    else:
        is_max = s == s.max()
    return ['background: lightgreen' if cell else '' for cell in is_max]
  
df.style.apply(highlight_max)


输出:

现在,来到突出显示部分。我们的目标是突出显示每列中具有最大值的单元格。

方法1:突出显示每列中具有最大值的单元格

我们将通过使用 DataFrame 属性的 highlight_max() 方法来做到这一点。 highlight_max() 方法接受 3 个参数,subset = 您要查找最大值的列的名称,color = 您要突出显示单元格的颜色的名称,axis = (0/1) 基于您使用的轴想找到最大值。

Python3

# Highlighting the maximum values of
# last 2 columns
df.style.highlight_max(color = 'lightgreen', axis = 0)

输出:

方法2:突出显示文本而不是单元格

Python3

# Defining custom function which returns 
# the list for df.style.apply() method
def highlight_max(s):
    is_max = s == s.max()
    return ['color: green' if cell else '' for cell in is_max]
  
df.style.apply(highlight_max)

输出:

方法 3:突出显示具有最大值的单元格

Python3

# Defining custom function which returns 
# the list for df.style.apply() method
def highlight_max(s):
    is_max = s == s.max()
    return ['background: lightgreen' if cell else '' for cell in is_max]
  
df.style.apply(highlight_max)

输出:

方法 4:突出显示具有最大值但不突出显示字符串值的单元格

Python3

# Defining custom function which returns
# the list for df.style.apply() method
def highlight_max(s):
    if s.dtype == np.object:
        is_max = [False for _ in range(s.shape[0])]
    else:
        is_max = s == s.max()
    return ['background: lightgreen' if cell else '' for cell in is_max]
  
df.style.apply(highlight_max)

输出: