【Pandas】pandas Series argmax

[复制链接]
发表于 2025-10-21 00:41:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Pandas2.2 Series

Computations descriptive stats

方法形貌Series.argsort([axis, kind, order, stable])用于返回 Series 中元素排序后的索引位置的方法Series.argmin([axis, skipna])用于返回 Series 中最小值索引位置的方法Series.argmax([axis, skipna])用于返回 Series 中最大值索引位置的方法pandas.Series.argmax

pandas.Series.argmax 是 Pandas 库中用于返回 Series 中最大值索引位置的方法。它会扫描整个 Series 并返回最大值对应的索引。
参数阐明


  • axis:{0 或 ‘index’}
    默以为 0,表现沿索引方向操纵。对于 Series 来说,这个参数通常不必要设置。
  • skipna:布尔值,默以为 True
    如果为 True,则忽略缺失值(NaN)。如果为 False,而且 Series 中存在缺失值,则返回 NaN。

示例及效果

示例 1:根本用法
  1. import pandas as pd
  2. # 创建一个示例 Series
  3. s = pd.Series([10, 20, 30, 40, 50])
  4. print("原始 Series:")
  5. print(s)
  6. # 使用 argmax 方法获取最大值的索引位置
  7. max_index = s.argmax()
  8. print("\n最大值的索引位置 (使用 argmax):")
  9. print(max_index)
复制代码
输出效果:
  1. 原始 Series:
  2. 0    10
  3. 1    20
  4. 2    30
  5. 3    40
  6. 4    50
  7. dtype: int64
  8. 最大值的索引位置 (使用 argmax):
  9. 4
复制代码
在这个例子中,argmax 返回了最大值 50 对应的索引位置 4。

示例 2:包罗重复值的 Series
  1. # 创建一个包含重复值的 Series
  2. s_with_duplicates = pd.Series([10, 30, 20, 30, 50, 50])
  3. print("原始 Series:")
  4. print(s_with_duplicates)
  5. # 使用 argmax 方法获取最大值的索引位置
  6. max_index_duplicates = s_with_duplicates.argmax()
  7. print("\n最大值的索引位置 (使用 argmax):")
  8. print(max_index_duplicates)
复制代码
输出效果:
  1. 原始 Series:
  2. 0    10
  3. 1    30
  4. 2    20
  5. 3    30
  6. 4    50
  7. 5    50
  8. dtype: int64
  9. 最大值的索引位置 (使用 argmax):
  10. 4
复制代码
在这个例子中,argmax 返回了第一个最大值 50 的索引位置 4。注意,纵然有多个最大值,argmax 只返回第一个出现的最大值的索引。

示例 3:处置处罚缺失值
  1. # 创建一个包含缺失值的 Series
  2. s_na = pd.Series([10, np.nan, 20, 30, np.nan, 50])
  3. print("原始 Series:")
  4. print(s_na)
  5. # 使用 argmax 方法并忽略缺失值
  6. max_index_skipna = s_na.argmax(skipna=True)
  7. print("\n最大值的索引位置 (使用 argmax 并忽略缺失值):")
  8. print(max_index_skipna)
  9. # 使用 argmax 方法不忽略缺失值
  10. max_index_no_skipna = s_na.argmax(skipna=False)
  11. print("\n最大值的索引位置 (使用 argmax 不忽略缺失值):")
  12. print(max_index_no_skipna)
复制代码
输出效果:
  1. 原始 Series:
  2. 0    10.0
  3. 1     NaN
  4. 2    20.0
  5. 3    30.0
  6. 4     NaN
  7. 5    50.0
  8. dtype: float64
  9. 最大值的索引位置 (使用 argmax 并忽略缺失值):
  10. 5
  11. 最大值的索引位置 (使用 argmax 不忽略缺失值):
  12. -1
复制代码
在这个例子中,当 skipna=True 时,argmax 忽略了缺失值并返回了最大值 50 的索引位置 5;当 skipna=False 时,由于存在缺失值,返回了 -1。

总结

argmax 方法用于返回 Series 中最大值的索引位置,支持忽略或生存缺失值的选项。在数据预处置处罚和分析中,该方法可以资助用户快速定位最大值的位置。通过公道设置参数,可以机动应对差异场景下的需求。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表