Выделите максимальное значение в каждом столбце в Pandas
Давайте обсудим, как выделить максимальные значения в Pandas Dataframe. Давайте сначала создадим фрейм данных:
Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {"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 Dataframedf = pd.DataFrame(dict) # Print Dataframedf |
Выход:

Теперь переходим к выделению. Наша цель - выделить ячейки с максимальными значениями в каждом столбце.
Метод 1: выделение ячейки с максимальным значением в каждом столбце
We will do this by using the highlight_max() method of DataFrame property. highlight_max() method takes 3 arguments, subset = name of the columns of which you want to find the maximum, color = name of the color with which you want to highlight the cell and axis = (0/1) based on which axis you want find the maximum.
Python3
# Highlighting the maximum values of# last 2 columnsdf.style.highlight_max(color = "lightgreen", axis = 0) |
Выход:

Method 2: Highlighting the text instead of cell
Python3
# Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s): is_max = s == s.max() return ["color: green" if cell else "" for cell in is_max] df.style.apply(highlight_max) |
Выход:

Method 3: Highlighting cell with maximum values
Python3
# Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s): is_max = s == s.max() return ["background: lightgreen" if cell else "" for cell in is_max] df.style.apply(highlight_max) |
Выход:

Method 4: Highlighting cell with maximum values but not highlighting the string values
Python3
# Defining custom function which returns# the list for df.style.apply() methoddef 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) |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.