Python之numpy.argpartition
13,455 阅读
在一个python程序中看到了关于numpy.argpartition的使用,因为没有接触过,所以上网搜索相关解释,但是除了官方的简单介绍之外,没有其他技术人员或博客有相关介绍。现在通过对程序中的这个问题的摸索,现在对该函数的使用具体实例化解释如下,参照示例可以更好的明白它的具体计算。
np.argpartition:划分重组数组,返回的是重组后数据的索引数组(切记这个输出形式)。这个可以很快地找出第 k 大的数的位置,以及大于 k (排在k后面)和 小于 k (排在k前面)的数的位置。下面具体看两种类型的例子: (1)示例1:
x = np.array([3, 4, 2, 1]) x[np.argpartition(x, 0)] >>array([1 4 2 3]) x[np.argpartition(x, 1)] >>array([1 2 4 3]) x[np.argpartition(x, 2)] >>array([1 2 3 4]) x[np.argpartition(x, 3)] >>array([2 1 3 4]) x[np.argpartition(x, 4)] >>ValueError: kth(=4) out of bounds (4)
(2)示例2:
y = np.array([[1, 2,4,7,3,5], [3, 4,1,6,9,0]])
b0=(0)
z0 = np.argpartition(y, b0, axis=1)
=>array([[0 1 2 3 4 5]
[5 1 2 3 4 0]])
