Pandas Series 的 idxmin() 方法是如何工作的?


为了获取 Pandas Series 对象最小值对应的标签名称,我们可以使用一个名为 idxmin() 的函数。这个 idxmin() 函数是 Pandas Series 构造函数的一个方法,用于获取 Series 元素中最小值的索引标签。

idxmin() 方法的输出是一个索引标签。如果给定的 Series 对象没有任何值(空 Series),它将返回 ValueError。此外,它会忽略缺失值,以便从给定 Series 对象的元素中识别最小值。

如果最小值在 Series 对象的多个元素中出现,则它将返回第一次出现的值的标签名称作为输出。

示例 1

让我们使用一个包含 8 个整数值的列表创建一个 Pandas Series 对象,然后应用 idxmin() 函数来获取 Series 对象最小值的行名称。

# import pandas package
import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series([23, 32, 11, 95, 40, 50, 81, 35])
print(s)

# Apply idxmin function
print('Output of idxmin:', s.idxmin())

输出

输出如下:

0    23
1    32
2    11
3    95
4    40
5    50
6    81
7    35
dtype: int64

Output of idxmin: 2

对于以下示例,Pandas Series 对象的 idxmin() 方法返回整数“2”,该整数表示给定 Series 对象中最小数的行名称。

示例 2

我们使用一个带有 date_range 索引标签的整数列表创建了一个 Pandas Series 对象。之后,我们在 Series 对象“s”的数据上应用 idxmin() 方法,以获取 Series “s”的最小值的索引标签。

import pandas as pd

# creating range sequence of dates
dates = pd.date_range('2021-01-01', periods=8, freq='m')

#creating pandas Series with date index
s = pd.Series([70, 42, 38, 16, 69, 17, 88, 74], index= dates)
print (s)

# Apply idxmin function
print('Output of idxmin:', s.idxmin())

输出

输出如下:

2021-01-31    70
2021-02-28    42
2021-03-31    38
2021-04-30    16
2021-05-31    69
2021-06-30    17
2021-07-31    88
2021-08-31    74
Freq: M, dtype: int64

Output of idxmin: 2021-04-30 00:00:00

此示例中 idxmin() 方法的输出是 **“2021-04-30 00:00:00”**,这意味着索引标签为“2021-04-30”的值在给定 Series 对象的元素中具有最小值。

更新于:2022年3月8日

313 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.