有没有办法使用np.min从矩阵中获得超过1个最小数?
x = np.array([[1,2,3],[4,5,6],[7,8,0]])
3个最小数字的预期结果
>>[0,1,2]
答案 0 :(得分:2)
一种方法是在展平视图上使用argsort
-
public function __construct ($x, ... $ignore) { ... }
效率更高的np.argpartition
-
x.ravel()[x.ravel().argsort()[:3]]
或者x.ravel()[x.ravel().argpartition(range(3))[:3]]
之后对其进行排序 -
sort
如果您不关心正在排序的数字,请跳过np.sort(x.ravel()[x.ravel().argpartition(3)[:3]])
-
sort
示例运行 -
x.ravel()[x.ravel().argpartition(3)[:3]]
答案 1 :(得分:1)
对数组进行展平和排序,并获得前3个元素。
sorted(x.flatten())[:3]
Out[275]: [0, 1, 2]
或更快的方法:
sorted(sum(x.tolist(),[]))[:3]
%timeit sorted(sum(x.tolist(),[]))[:3]
The slowest run took 7.38 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.14 µs per loop
%timeit sorted(x.flatten())[:3]
The slowest run took 11.54 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.97 µs per loop