查看数组numpy前K个数和后K个数
numpy.argpartition(a, kth, axis=-1, kind=‘introselect’, order=None)
一般numpy中以arg开头的函数都是返回下标,而不改变原数组。
参数a是指传入的Numpy.array
参数kth是指列表中下标为k位置应该放置该数组中第k大的值
import numpy as np arr = np.array([3, 9, 1, 0, 2, 1, 7, 5])
例如:
返回的是下标,由于python是从0开始计算而非1,所以kth=0表示第0位置应当放置该数组中最小(排名第0的数)的值,使用如下方法输出索引:
idx = np.argpartition(arr, 0) # 输出结果 [3 1 2 0 4 5 6 7]
比如 idx = np.argpartition(arr, 3),表明第3个索引位置放置第3小的数据。两边一边比他小。一边比他大,但是保持原数组位置不变
idx = np.argpartition(arr, 3) # 输出结果索引为 [3, 5, 2, 4, 0, 1, 6, 7]
那么这时如果想要选取前3小的数据只需要
arr[idx[:3]] # 输出结果为 [0, 1, 1]



