在Pandas中突出显示每一列的最大值
让我们来讨论如何在Pandas数据框架中突出显示最大值。让我们首先制作一个数据框架。
示例:
# 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
输出:
现在,来看看突出显示的部分。我们的目标是突出显示每一列中具有最大值的单元格。
方法1:突出显示每一列中具有最大数值的单元格。
我们将通过使用DataFrame属性的highlight_max()方法来做到这一点。 highlight_max()方法需要3个参数,subset = 你想找到最大值的列的名称,color = 你想突出显示单元格的颜色名称, axis = (0/1) 基于你想找到最大值的轴。
# Highlighting the maximum values of
# last 2 columns
df.style.highlight_max(color = 'lightgreen', axis = 0)
输出:
方法2:突出显示文本而不是单元格。
# 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:突出显示具有最大数值的单元格。
# 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:突出显示有最大值的单元格,但不突出显示字符串的值。
# 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)
输出: