How to calculate the minimum and maximum value of a column in a Pandas DataFrame?
Published on Aug. 22, 2023, 12:19 p.m.
To calculate the minimum and maximum value of a column in a Pandas DataFrame, you can use the min()
and max()
methods respectively on the column. Here is an example:
import pandas as pd
# Create a sample DataFrame with columns 'A' and 'B'
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# Calculate the minimum and maximum values of the 'B' column
min_val = df['B'].min()
max_val = df['B'].max()
# Print the minimum and maximum values
print('Minimum value:', min_val)
print('Maximum value:', max_val)
This code will output the following minimum and maximum values:
Minimum value: 4
Maximum value: 6
In this example, we first created a DataFrame with columns ‘A’ and ‘B’. We then calculated the minimum and maximum values of the ‘B’ column using the min()
and max()
methods respectively.
You can also calculate the minimum and maximum values for multiple columns by passing a list of column names to the min()
or max()
methods. For example:
# Calculate the minimum and maximum values of columns 'A' and 'B'
min_vals = df[['A', 'B']].min()
max_vals = df[['A', 'B']].max()
# Print the minimum and maximum values
print('Minimum values:', min_vals)
print('Maximum values:', max_vals)
This will output the following minimum and maximum values for columns ‘A’ and ‘B’:
Minimum values:
A 1
B 4
dtype: int64
Maximum values:
A 3
B 6
dtype: int64
Note that the min()
and max()
methods return scalar values for single columns and Series objects for multiple columns, so you may need to access the specific value(s) you want from the Series object if you use them for multiple columns.