在Python Pandas中突出显示最后两列的最大值

在Python Pandas中突出显示最后两列的最大值

在这篇文章中,我们将讨论如何在Pandas Dataframe中突出显示最大值。首先,让我们做一个数据框架。
示例:

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

输出:

在Pandas中突出显示最后两列的最大值 - Python

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

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

我们将通过使用DataFrame属性的highlight_max()方法来做到这一点。 highlight_max()方法需要3个参数。

  • subset:你想找到最大的列的名称。
  • color:你想要突出显示的单元格的颜色名称。
  • axis: (0/1) 基于你想找到最大的轴。

示例:

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

输出:

在Pandas中突出显示最后两列的最大值 - Python

方法2:我们不使用列名,而将其概括为最后两列

示例:

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

输出:

在Pandas中突出显示最后两列的最大值 - Python

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

示例:

# 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, subset = df.columns[-2:])

输出:

在Pandas中突出显示最后两列的最大值 - Python

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

示例:

# 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, subset = df.columns[-2:])

输出:

在Pandas中突出显示最后两列的最大值 - Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程