如何获取 pandas 系列中最大值的位置?
pandasserver side programmingprogramming更新于 2025/5/18 10:52:17
在 pandas 系列构造函数中,有一个名为 argmax() 的方法,用于获取系列数据中最大值的位置。
pandas 系列是一个具有行索引值的单维数据结构对象。通过使用行索引值,我们可以访问数据。
pandas 系列中的 argmax() 方法用于获取系列对象最大值的位置索引。 argmax 方法的输出是一个整数值,它指的是最大值所在的位置。
示例 1
# 导入 pandas 包
import pandas as pd
import numpy as np
# 创建一个 pandas 系列
s = pd.Series(np.random.randint(10,100, 10))
print(s)
# 应用 argmax 函数
print('argmax 的输出', s.argmax())
解释
让我们创建一个 pandas 系列对象,其中包含 10 到 100 范围内的 10 个随机整数值,并应用 argmax() 函数获取系列值中最大值的位置。
输出
0 81 1 94 2 75 3 13 4 17 5 42 6 45 7 29 8 25 9 59 dtype: int32 argmax 的输出: 1
pandas 系列对象的 argmax() 方法返回一个整数值"1"对于以下示例,该整数值表示给定系列元素的最大值的位置。
示例 2
import pandas as pd
import numpy as np
# 创建 pandas Series 对象
series = pd.Series({'Black':10, 'White':29,'Red':82, 'Blue':56,'Green':67})
print(series)
# 应用 argmax 函数
print('argmax 的输出:',series.argmax())
解释
在下面的示例中,我们创建了一个 pandas.Series 对象使用 Python 字典创建 “series”,生成的系列具有带有整数数据的命名索引标签。之后,我们对系列对象的数据应用 argmax() 方法以获取最大数字的位置。
输出
Black 10 White 29 Red 82 Blue 56 Green 67 dtype: int64 argmax 的输出: 2
对于以下示例,argmax() 方法的输出为 2,这意味着索引标签"Red"处的值具有最大值。
如果最大值在多个位置可用,则 argmax 方法将返回第一行位置作为输出。

