深度阅读

How to calculate the minimum and maximum value of a column in a Pandas DataFrame?

作者
作者
2023年08月22日
更新时间
16.72 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。