Python获取Numpy数组前N个最大值及索引的方法

Oliver
Oliver
发布时间:2026-10-14| 6人浏览过
原创

本文介绍了在Python中获取Numpy数组前N个最大值及其索引的两种常用方法。首先通过numpy.argsort函数对数组排序获取索引,再反向切片得到Top N结果;其次利用heapq模块的nlargest函数直接提取最大值及其对应索引。文章包含具体代码示例与输出结果分析,适用于数据筛选与排序场景。

实现该功能主要依赖于numpy库中的argsort()函数。该函数的完整原型定义如下:


numpy.argsort(a, axis=-1, kind='quicksort', order=None)
'''
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.
'''
Parameters: 
a : array_like
Array to sort.
 
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
 
kind : {‘quicksort', ‘mergesort', ‘heapsort', ‘stable'}, optional
Sorting algorithm.
 
order : str or list of str, optional
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
 
Returns: 
index_array : ndarray, int
Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. More generally, np.take_along_axis(a, index_array, axis=a) always yields the sorted a, irrespective of dimensionality.
 

具体使用示例如下所示:


import numpy as np
top_k=3
arr = np.array([1, 3, 2, 4, 5])
top_k_idx=arr.argsort()[::-1][0:top_k]
print(top_k_idx)
#[4 3 1]

补充说明:在Python中获取数组或列表中最大的N个数(Top N)或最小的N个数(Top K)的通用思路。


import numpy as np
a = np.array([1,4,3,5,2])
b = np.argsort(a)
print(b)

代码执行后的输出结果为:[0 4 2 1 3]

该结果的含义是:原数组中索引为0的元素最小,索引为3的元素最大。

根据排序结果可推导出的大小关系为:a[0]<a[4]<a[2]<a[1]<a[3]

补充内容:介绍如何利用Python获取数组或列表中最大的N个数,并同时获取这些最大值在原数组中的索引位置。

具体实现代码如下:


import heapq
 
a=[43,5,65,4,5,8,87]
re1 = heapq.nlargest(3, a) #求最大的三个元素,并排序
re2 = map(a.index, heapq.nlargest(3, a)) #求最大的三个索引    nsmallest与nlargest相反,求最小
print(re1)
print(list(re2)) #因为re2由map()生成的不是list,直接print不出来,添加list()就行了

程序运行后的输出结果如下:

结果re1(最大值列表):[87, 65, 43]

结果re2(最大值对应的索引列表):[6, 2, 0]

以上内容为个人经验分享,旨在为读者提供参考。欢迎大家支持本站,如有问题欢迎交流。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。