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

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

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

在本文中,我们将讨论如何突出显示 Pandas Dataframe 中的最小值。所以,让我们首先制作一个数据框:

Python3
# 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, 45, 21, 22],
  'Marks': [90, 84, 33, 87, 82]
}
  
# Converting Dictionary to 
# Pandas Dataframe
df = pd.DataFrame(dict)
  
# Print Dataframe
print(df)


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


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


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


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


输出:

数据框

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

方法一:使用df.style.highlight_min()方法。

示例:突出显示每列中具有最小值的单元格。

Python3

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

输出:

方法二:使用df.style.apply()方法。

示例 1:突出显示文本而不是单元格。

Python3

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

输出:

示例 2:突出显示具有最小值的单元格。

Python3

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

输出:

示例 3:突出显示具有最小值但不突出显示字符串值的单元格。

Python3

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

输出: