如何从Python中的 Pandas 数据框中获取最大值?
Python Pandas max()函数 返回请求轴上的最大值。
Syntax: dataframe.max(axis)
where,
- axis=0 specifies column
- axis=1 specifies row
示例 1:获取数据框行中的最大值
要获取数据帧行中的最大值,只需调用 max()函数并将轴设置为 1。
Syntax: dataframe.max(axis=1)
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 5 rows and 4 columns
data = pd.DataFrame({
'name': ['sravan', 'ojsawi', 'bobby',
'rohith', 'gnanesh'],
'subjects': ['java', 'php', 'html/css',
'python', 'R'],
'marks': [98, 90, 78, 91, 87],
'age': [11, 23, 23, 21, 21]
})
# display dataframe
print(data)
# get the maximum in row
data.max(axis=1)
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 5 rows and 4 columns
data = pd.DataFrame({
'name': ['sravan', 'ojsawi', 'bobby',
'rohith', 'gnanesh'],
'subjects': ['java', 'php', 'html/css',
'python', 'R'],
'marks': [98, 90, 78, 91, 87],
'age': [11, 23, 23, 21, 21]
})
# display dataframe
print(data)
# get the maximum in column
data.max(axis=0)
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 5 rows and 4 columns
data = pd.DataFrame({
'name': ['sravan', 'ojsawi', 'bobby',
'rohith', 'gnanesh'],
'subjects': ['java', 'php', 'html/css',
'python', 'R'],
'marks': [98, 90, 78, 91, 87],
'age': [11, 23, 23, 21, 21]
})
# display dataframe
print(data)
# get the max in name column
print(data['name'].max())
# get the max in subjects column
print(data['subjects'].max())
# get the max in age column
print(data['age'].max())
# get the max in marks column
print(data['marks'].max())
输出:
示例 2:获取列中的最大值
要获取列中的最大值,只需使用设置为 0 的轴调用 max()函数。
Syntax: dataframe.max(axis=0)
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 5 rows and 4 columns
data = pd.DataFrame({
'name': ['sravan', 'ojsawi', 'bobby',
'rohith', 'gnanesh'],
'subjects': ['java', 'php', 'html/css',
'python', 'R'],
'marks': [98, 90, 78, 91, 87],
'age': [11, 23, 23, 21, 21]
})
# display dataframe
print(data)
# get the maximum in column
data.max(axis=0)
输出:
示例 3:获取特定列中的最大值
要获取特定列中的最大值,请使用特定列名和 max()函数调用数据框。
Syntax: dataframe[‘column_name’].max()
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 5 rows and 4 columns
data = pd.DataFrame({
'name': ['sravan', 'ojsawi', 'bobby',
'rohith', 'gnanesh'],
'subjects': ['java', 'php', 'html/css',
'python', 'R'],
'marks': [98, 90, 78, 91, 87],
'age': [11, 23, 23, 21, 21]
})
# display dataframe
print(data)
# get the max in name column
print(data['name'].max())
# get the max in subjects column
print(data['subjects'].max())
# get the max in age column
print(data['age'].max())
# get the max in marks column
print(data['marks'].max())
输出: