Minimum & Maximum in Python – Get Min & Max in List & DataFrame (4 Examples)

This article illustrates how to calculate the maximum and minimum in the Python programming language.

Example 1: Calculating the Minimum & Maximum of a List Object

my_lt = [10, 6, 2, 2, 15, 20, 3, 7, 4]      # Constructing a list in Python
print(my_lt)
# [10, 6, 2, 2, 15, 20, 3, 7, 4]
print(min(my_lt))                           # Computing the min of a list
# 2
print(max(my_lt))                           # Computing the max of a list
# 20

Example 2: Calculating the Minimum & Maximum of the Columns in a pandas DataFrame

import pandas as pd                         # Import pandas
my_df = pd.DataFrame({'A':range(10, 17),    # Constructing a pandas DataFrame
                      'B':[6, 1, 8, 5, 3, 8, 9],
                      'C':range(2, 9),
                      'GRP':['gr1', 'gr2', 'gr1', 'gr3', 'gr1', 'gr2', 'gr3']})
print(my_df)
#     A  B  C  GRP
# 0  10  6  2  gr1
# 1  11  1  3  gr2
# 2  12  8  4  gr1
# 3  13  5  5  gr3
# 4  14  3  6  gr1
# 5  15  8  7  gr2
# 6  16  9  8  gr3
print(my_df.min())                          # Computing the min of all columns
# A       10
# B        1
# C        2
# GRP    gr1
# dtype: object
print(my_df.max())                          # Computing the max of all columns
# A       16
# B        9
# C        8
# GRP    gr3
# dtype: object

Example 3: Calculating the Minimum & Maximum of the Columns in a pandas DataFrame by Group

print(my_df.groupby('GRP').min())           # Computing the column minima by group
#       A  B  C
# GRP          
# gr1  10  3  2
# gr2  11  1  3
# gr3  13  5  5
print(my_df.groupby('GRP').max())           # Computing the column maxima by group
#       A  B  C
# GRP          
# gr1  14  8  6
# gr2  15  8  7
# gr3  16  9  8

Example 4: Calculating the Minimum & Maximum of the Rows in a pandas DataFrame

print(my_df.min(axis = 1))                  # Computing the min of all rows
# 0    2
# 1    1
# 2    4
# 3    5
# 4    3
# 5    7
# 6    8
# dtype: int64
print(my_df.max(axis = 1))                  # Computing the max of all rows
# 0    10
# 1    11
# 2    12
# 3    13
# 4    14
# 5    15
# 6    16
# dtype: int64

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top