Как найти минимальное и максимальное значение в Pandas
Нахождение максимального и минимального значения в Pandas — зачастую, необходимая операция для анализа данных. Поэтому предлагаю попрактиковаться на примере тренировочного датасета: отыскать предельные значения и вывести строки с этими значениями на экран.
Действовать будем по плану:
Сначала поработаем с максимальными значениями:
- Найдем максимальное значение:
- для каждого столбца таблицы;
- в определенном столбце таблицы
- Выведем на экран строки с максимальными значениями
Затем поработаем с минимальными значениями:
- Найдем минимальное значение:
- для каждого столбца таблицы;
- в определенном столбце таблицы
- Выведем на экран строки с минимальными значениями
Загрузка датасета
Для наглядности будем использовать тренировочный датасет с пропорциями некоторых продуктов для приготовления кондитерских изделий. Скачать датасет можно по ссылке: products.csv. Итак, загрузим файл с данными:
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11)
Выведем таблицу на экран:
Названия десертов и наименования продуктов представлены в качестве индексов таблицы. Числовое значение в каждой ячейке, расположенной на пересечении строки с десертом и колонки с наименованием продукта — это количество продукта в граммах, необходимое для приготовления 1 кг. изделия.
После загрузки датасета можно переходить к реализации нашего плана и отыскать предельные значения!
Работаем с максимальными значениями
1. Ищем максимальное значение:
# для каждого столбца таблицы:
Получим максимальный вес каждого продукта. Для этого найдем максимальные значения в каждом столбце таблицы с помощью функции max() и выведем их на экран. Применим функцию max() ко всей таблице data:
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11) #Получим максимальные значения в каждом столбце maximums = data.max() # выведем результат на экран print(maximums)
Полученный результат — максимальные значения в каждом столбце
egg 200 sugar 282 flour 900 butter 235 dtype: int64
# в определенном столбце таблицы:
Узнаем, сколько потребуется сахара для приготовления 1 кг. самого сладкого блюда из представленных в таблице. Для этого получим максимальное значение в столбце «sugar» с помощью функции max(). На этот раз применим функцию max() к столбцу «sugar»:
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11) #Получим максимальное значение в столбце "sugar" max_sugar = data['sugar'].max() # выведем результат на экран print(max_sugar)
Полученный результат — максимальное значение в столбце «sugar»
282
Теперь мы знаем, что в 1 кг. самого сладкого блюда из таблицы data содержится 282 грамм сахара. Однако, хотелось бы узнать название этого блюда, а еще лучше — вывести всю строку с информацией о нем:
2. Выводим на экран строку с максимальным значением
Для этого используем полученное значение с максимальным количеством сахара (data[‘sugar’].max()) и выведем строку, для которой выполняется условие data[‘sugar’]==data[‘sugar’].max():
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11) # Найдем строку с максимальным значением str = data[data['sugar']==data['sugar'].max()] # Выведем строку на экран print(str)
Полученный результат — строка таблицы data с максимальным значением
В соответствии с полученным результатом, самым сладким блюдом из представленных в таблице data являются печенья!
Работаем с минимальными значениями
Главным козырем при нахождении минимальных значений в данных является функция min(). Рассмотрим варианты ее применения для получения желаемого результата:
1. Ищем минимальное значение:
# для каждого столбца таблицы
Выведем на экран минимальные значения в каждом столбце таблицы с помощью функции min(). Для этого применим функцию min() ко всей таблице data:
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11) # Найдем минимальные значения в каждом столбце таблицы minimums = data.min() # Выведем результат на экран print(minimums)
Полученный результат — минимальные значения в каждом столбце
egg 50 sugar 0 flour 50 butter 0 dtype: int64
# в определенном столбце таблицы:
Найдем минимальное значение в столбце «sugar» с помощью функции min():
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11) # Найдем минимальное значение в столбце «sugar» min_sugar = data['sugar'].min() # Выведем найденное значение на экран print(min_sugar)
Результат на экране — минимальное значение в столбце «sugar»:
0
Выходит, что среди размещенных в таблице блюд присутствуют несладкие изделия. Давайте узнаем, какой представитель выпечки самый несладкий: выведем на экран строку с его именем!
2. Выводим на экран строку с минимальным значением
Для этого найдем строку, для которой значение в столбце ‘sugar’ совпадает с найденным ранее минимальным количеством сахара: data[‘sugar’]==data[‘sugar’].min():
import pandas as pd data = pd.read_csv('products.csv', sep=';', index_col='dish') data.head(11) # Найдем строку с минимальным значением str = data[data['sugar']==data['sugar'].min()] # выведем строку на экран print(str)
Результат — строка с минимальным значением в столбце «sugar»:
Таким образом, нам удалось выяснить, что в пасте (в соответствии с таблицей data) не содержится сахара. Ах, вот почему она не сладкая! 😉
Теперь, когда все технологические секреты раскрыты, а предельные значения найдены, подведем итоги:
У нас появился Telegram-канал для изучающих Python! Подписывайтесь по ссылке: «Кодим на Python! Вместе «питонить» веселее! 😉
Коротко о поиске максимальных и минимальных значений в pandas:
Дано: датасет data c числовыми значениями в столбцах: «egg», «sugar», «flour», «butter».
1. Получим максимальные / минимальные значения для каждого столбца:
# Максимальные значения - maximums maximums = data.max() # Минимальные значения - minimums minimums = data.min()
2. Получим максимальное / минимальное значение для столбца «sugar»:
# Максимальное значение в столбце "sugar" max_sugar = data['sugar'].max() # Минимальное значение в столбце "sugar" min_sugar = data['sugar'].min()
3. Выведем на экран строку с максимальным / минимальным значением в столбце «sugar»:
# Найдем строку с максимальным значением str = data[data['sugar']==data['sugar'].max()] # выведем строку на экран print(str) # Найдем строку с минимальным значением str = data[data['sugar']==data['sugar'].min()] # выведем строку на экран print(str)
In this article, we are going to discuss how to find the maximum value and its index position in columns and rows of a Dataframe.
Create Dataframe to Find max values & position of columns or rows
Python3
import
numpy as np
import
pandas as pd
matrix
=
[(
10
,
56
,
17
),
(np.NaN,
23
,
11
),
(
49
,
36
,
55
),
(
75
, np.NaN,
34
),
(
89
,
21
,
44
)
]
abc
=
pd.DataFrame(matrix, index
=
list
(
'abcde'
), columns
=
list
(
'xyz'
))
abc
Output:
Time complexity: O(n) where n is the number of elements in the matrix.
Auxiliary space: O(n) where n is the number of elements in the matrix.
Find maximum values in columns and rows in Pandas
Pandas dataframe.max() method finds the maximum of the values in the object and returns it. If the input is a series, the method will return a scalar which will be the maximum of the values in the series. If the input is a Dataframe, then the method will return a series with a maximum of values over the specified axis in the Dataframe. The index axis is the default axis taken by this method.
Get the maximum values of every column in Python
To find the maximum value of each column, call the max() method on the Dataframe object without taking any argument. In the output, We can see that it returned a series of maximum values where the index is the column name and values are the maxima from each column.
Python3
maxValues
=
abc.
max
()
print
(maxValues)
Output:
Get max value from a row of a Dataframe in Python
For the maximum value of each row, call the max() method on the Dataframe object with an argument axis=1. In the output, we can see that it returned a series of maximum values where the index is the row name and values are the maxima from each row.
Python3
maxValues
=
abc.
max
(axis
=
1
)
print
(maxValues)
Output:
Get the maximum values of every column without skipping NaN in Python
From the above examples, NaN values are skipped while finding the maximum values on any axis. By putting skipna=False we can include NaN values also. If any NaN value exists it will be considered as the maximum value.
Python3
maxValues
=
abc.
max
(skipna
=
False
)
print
(maxValues)
Output:
Get maximum values from multiple columns in Python
To get the maximum value of a single column see the following example
Python3
maxClm
=
df[
'x'
].
max
()
print
(
"Maximum value in column 'x': "
)
print
(maxClm)
Output:
Get max value in one or more columns
A list of columns can also be passed instead of a single column to find the maximum values of specified columns
Python3
maxValues
=
df[[
'x'
,
'z'
]].
max
()
print
(
"Maximum value in column 'x' & 'z': "
)
print
(maxValues)
Output:
Find the maximum position in columns and rows in Pandas
Pandas dataframe.idxmax() method returns the index of the first occurrence of maximum over the requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded.
Find the row index which has the maximum value
It returns a series containing the column names as index and row as index labels where the maximum value exists in that column.
Python3
maxValueIndex
=
df.idxmax()
print
(
"Maximum values of columns are at row index position :"
)
print
(maxValueIndex)
Output:
Find the column name which has the maximum value
It returns a series containing the rows index labels as index and column names as values where the maximum value exists in that row.
Python3
maxValueIndex
=
df.idxmax(axis
=
1
)
print
(
"Max values of row are at following columns :"
)
print
(maxValueIndex)
Output:
Last Updated :
03 Feb, 2023
Like Article
Save Article
Данная ошибка говорит о том, что столбца с таким наименованием нет в DataFrame.
Воспроизведение ошибки:
In [20]: df = pd.DataFrame({"fixed assets value": [1,2,3,], "gross output at constant prices": [11,12,13]})
In [21]: df.columns.to_list()
Out[21]: ['fixed assets value', 'gross output at constant prices']
In [22]: df.columns = df.columns.str.replace("s+", "_")
In [23]: df
Out[23]:
fixed_assets_value gross_output_at_constant_prices
0 1 11
1 2 12
2 3 13
теперь попытаемся найти максимум/минимум для существующих и несуществующих столбцов:
In [24]: df.fixed_assets_value.max()
Out[24]: 3
In [25]: df.gross_output_at_constant_prices.min()
Out[25]: 11
In [26]: df.non_existing_col.max()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
...
AttributeError: 'DataFrame' object has no attribute 'non_existing_col'
PS более идиоматично/правильно обращаться к столбцам фрейма используя квадратные скобки — это будет работать для любых наименований столбцов, даже для таких, которые содержат пробелы или символы пунктуации.
In [27]: df = pd.DataFrame({"col 1": [1,2], "col,2;": [10,20]})
In [28]: df
Out[28]:
col 1 col,2;
0 1 10
1 2 20
In [29]: df["col,2;"].mean()
Out[29]: 15.0
разумеется обратиться к такому столбцу как к атрибуту не получится:
In [30]: df.col,2;
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
...
AttributeError: 'DataFrame' object has no attribute 'col'
PPS чтобы получить полный список столбцов DataFrame в виде обычного списка:
In [31]: df.columns.to_list()
Out[31]: ['col 1', 'col,2;']
Чтобы найти максимальное значение в Pandas DataFrame, вы можете использовать метод pandas.DataFrame.max(). Используя max(), вы можете найти максимальное значение по оси: по строкам или по столбцам, или максимум для всего DataFrame.
Пример 1: по столбцам
В этом примере мы рассчитаем максимальное значение по столбцам.
Узнаем самые высокие оценки, полученные студентами по предметам.
import pandas as pd mydictionary = {'physics': [68, 74, 77, 78], 'chemistry': [84, 56, 73, 69], 'algebra': [78, 88, 82, 87]} # create dataframe df_marks = pd.DataFrame(mydictionary) print('DataFramen----------') print(df_marks) # calculate max along columns mean = df_marks.max() print('nMaximum Valuen------') print(mean)
Вывод:
DataFrame ---------- physics chemistry algebra 0 68 84 78 1 74 56 88 2 77 73 82 3 78 69 87 Maximum Value ------ physics 78 chemistry 84 algebra 88 dtype: int64
Пример 2: по строке
В этом примере мы найдем максимум по строкам DataFrame. Это приводит к нахождению максимальных оценок, полученных студентом по любому предмету.
import pandas as pd mydictionary = {'physics': [68, 74, 77, 78], 'chemistry': [84, 56, 73, 69], 'algebra': [78, 88, 82, 87]} # create dataframe df_marks = pd.DataFrame(mydictionary) print('DataFramen----------') print(df_marks) # calculate max along columns mean = df_marks.max(axis=1) print('nMaximum Valuen------') print(mean)
Вывод:
DataFrame ---------- physics chemistry algebra 0 68 84 78 1 74 56 88 2 77 73 82 3 78 69 87 Maximum Value ------ 0 84 1 88 2 82 3 87 dtype: int64
Пример 3
В этом примере мы узнаем максимальное значение в DataFrame независимо от строк или столбцов.
В предыдущих примерах мы нашли максимальное значение по столбцам и строкам соответственно. В этих случаях примените функцию max() к результату функции max(), вы получите максимум полного DataFrame.
import pandas as pd mydictionary = {'physics': [68, 74, 77, 78], 'chemistry': [84, 56, 73, 69], 'algebra': [78, 88, 82, 87]} # create dataframe df_marks = pd.DataFrame(mydictionary) print('DataFramen----------') print(df_marks) # calculate max of whole DataFrame mean = df_marks.max().max() print('nMaximum Valuen------') print(mean)
Вывод:
DataFrame ---------- physics chemistry algebra 0 68 84 78 1 74 56 88 2 77 73 82 3 78 69 87 Maximum Value ------ 88
В этом руководстве по Pandas мы узнали, как получить максимальное значение всего DataFrame, по столбцу (столбцам) и строкам.
This div height required for enabling the sticky sidebar
Pandas dataframes are great for analyzing and manipulating data. In this tutorial, we will look at how to get the max value in one or more columns of a pandas dataframe with the help of some examples.
If you prefer a video tutorial over text, check out the following video detailing the steps in this tutorial –
Pandas max()
function
You can use the pandas max()
function to get the maximum value in a given column, multiple columns, or the entire dataframe. The following is the syntax:
# df is a pandas dataframe # max value in a column df['Col'].max() # max value for multiple columns df[['Col1', 'Col2']].max() # max value for each numerical column in the dataframe df.max(numeric_only=True) # max value in the entire dataframe df.max(numeric_only=True).max()
It returns the maximum value or values depending on the input and the axis (see the examples below).
Examples
Let’s look at some use-case of the pandas max()
function. First, we’ll create a sample dataframe that we will be using throughout this tutorial.
import numpy as np import pandas as pd # create a pandas dataframe df = pd.DataFrame({ 'Name': ['Neeraj Chopra', 'Jakub Vadlejch', 'Vitezslav Vesely', 'Julian Weber', 'Arshad Nadeem'], 'Country': ['India', 'Czech Republic', 'Czech Republic', 'Germany', 'Pakistan'], 'Attempt1': [87.03, 83.98, 79.79, 85.30, 82.40], 'Attempt2': [87.58, np.nan, 80.30, 77.90, np.nan], 'Attempt3': [76.79, np.nan, 85.44, 78.00, 84.62], 'Attempt4': [np.nan, 82.86, np.nan, 83.10, 82.91], 'Attempt5': [np.nan, 86.67, 84.98, 85.15, 81.98], 'Attempt6': [84.24, np.nan, np.nan, 75.72, np.nan] }) # display the dataframe df
Output:
Here we created a dataframe containing the scores of the top five performers in the men’s javelin throw event final at the Tokyo 2020 Olympics. The attempts represent the throw of the javelin in meters.
1. Max value in a single pandas column
To get the maximum value in a pandas column, use the max() function as follows. For example, let’s get the maximum value achieved in the first attempt.
# max value in Attempt1 print(df['Attempt1'].max())
Output:
87.03
We get 87.03 meters as the maximum distance thrown in the “Attemp1”
Note that you can get the index corresponding to the max value with the pandas idxmax() function. Let’s get the name of the athlete who threw the longest in the first attempt with this index.
# index corresponding max value i = df['Attempt1'].idxmax() print(i) # display the name corresponding this index print(df['Name'][i])
Output:
0 Neeraj Chopra
You can see that the max value corresponds to “Neeraj Chopra”.
2. Max value in two pandas columns
You can also get the max value of multiple pandas columns with the pandas min() function. For example, let’s find the maximum values in “Attempt1” and “Attempt2” respectively.
# get max values in columns "Attempt1" and "Attempt2" print(df[['Attempt1', 'Attempt2']].max())
Output:
Attempt1 87.03 Attempt2 87.58 dtype: float64
Here, created a subset dataframe with the columns we wanted and then applied the max() function. We get the maximum value for each of the two columns.
3. Max value for each column in the dataframe
Similarly, you can get the max value for each column in the dataframe. Apply the max function over the entire dataframe instead of a single column or a selection of columns. For example,
# get max values in each column of the dataframe print(df.max())
Output:
Name Vitezslav Vesely Country Pakistan Attempt1 87.03 Attempt2 87.58 Attempt3 85.44 Attempt4 83.1 Attempt5 86.67 Attempt6 84.24 dtype: object
We get the maximum values in each column of the dataframe df. Note that we also get max values for text columns based on their string comparisons in python.
If you only want the max values for all the numerical columns in the dataframe, pass numeric_only=True
to the max() function.
# get max values of only numerical columns print(df.max(numeric_only=True))
Output:
Attempt1 87.03 Attempt2 87.58 Attempt3 85.44 Attempt4 83.10 Attempt5 86.67 Attempt6 84.24 dtype: float64
4. Max value between two pandas columns
What if you want to get the maximum value between two columns?
You can do so by using the pandas max() function twice. For example, let’s get the maximum value considering both “Attempt1” and “Attempt2”.
# max value over two columns print(df[['Attempt1', 'Attempt2']].max().max())
Output:
87.58
We get 87.58 as the maximum distance considering the first and the second attempts together.
5. Max value in the entire dataframe
You can also get the single biggest value in the entire dataframe. For example, let’s get the biggest value in the dataframe df irrespective of the column.
# mav value over the entire dataframe print(df.max(numeric_only=True).max())
Output:
87.58
Here we apply the pandas max() function twice. First time to get the max values for each numeric column and then to get the max value among them.
For more on the pandas max() function, refer to its documentation.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
-
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.
View all posts