如何获取 pandas 系列中最小值的位置?

pandasserver side programmingprogramming更新于 2025/5/18 10:37:17

要获取 pandas 系列对象中最小值的位置,我们可以使用名为 argmin() 的函数。

argmin() 是 pandas 系列构造函数的方法,用于获取系列中最小值的行位置。argmin() 方法的输出是一个整数值。如果 pandas 系列对象具有 Nan 值,则 argmin() 方法将通过忽略这些 Nan 值来识别最小数字。

如果最小值位于多个索引位置,则将第一个出现值的位置作为输出。

示例 1

# 导入 pandas 包
import pandas as pd
import numpy as np

# 创建 pandas 系列
s = pd.Series(np.random.randint(1,100, 10))
print(s)

# 应用 argmin 函数
print('argmin 的输出:', s.argmin())

解释

让我们创建一个 pandas 系列对象,其中包含 10 个介于 1 到 100 之间的随机整数值范围,然后应用 argmin 函数获取系列对象最小值的位置。

首先,我们导入了 NumPy 包来创建一系列随机整数值。

输出

0 76
1 58
2 42
3 81
4  7
5 85
6 75
7 25
8 61
9 57
dtype: int32

Output of argmin: 4

pandas 系列对象的 argmin() 方法返回一个整数值"4"对于以下示例,该整数值表示给定系列对象的最小值的位置。

示例 2

import pandas as pd

# 创建日期范围序列
dates = pd.date_range('2021-06-01', periods=6, freq='D')

# 创建带有日期索引的 pandas 系列
s = pd.Series([43,21,40,54,10,23], index= dates)
print (s)

# 应用 argmin 函数
print('argmin 的输出:', s.argmin())

解释

让我们使用整数列表创建另一个 pandas 系列对象带有 date_range 索引标签。之后,对系列对象"s"的数据应用 argmin() 方法以获取给定系列对象的最小值的位置。

输出

2021-06-01 43
2021-06-02 21
2021-06-03 40
2021-06-04 54
2021-06-05 10
2021-06-06 23
Freq: D, dtype: int64

Output of argmin: 4

此示例的 argmin() 方法的输出是整数值"4",这意味着索引标签"2021-06-05"处的值在给定系列对象中存在的数据中具有最小值。


相关文章