0
有沒有一種方法可以使用np.min從矩陣中獲取多於1個最小數?從np.min獲得3個最小數(array)
x = np.array([[1,2,3],[4,5,6],[7,8,0]])
3個最小號碼
預期結果>>[0,1,2]
有沒有一種方法可以使用np.min從矩陣中獲取多於1個最小數?從np.min獲得3個最小數(array)
x = np.array([[1,2,3],[4,5,6],[7,8,0]])
3個最小號碼
預期結果>>[0,1,2]
拼合並對數組進行排序並獲得前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
的一種方法是對flattend視圖中使用argsort
-
x.ravel()[x.ravel().argsort()[:3]]
更高性能一個與np.argpartition
-
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]]
採樣運行 -
In [44]: x
Out[44]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 0]])
In [45]: x.ravel()[x.ravel().argsort()[:3]]
Out[45]: array([0, 1, 2])
In [48]: x.ravel()[x.ravel().argpartition(range(3))[:3]]
Out[48]: array([0, 1, 2])
In [52]: np.sort(x.ravel()[x.ravel().argpartition(3)[:3]])
Out[52]: array([0, 1, 2])
In [47]: x.ravel()[x.ravel().argpartition(3)[:3]]
Out[47]: array([0, 1, 2])
'argpartition'是要走的路。它的* O(log n)*其中'argsort'是* O(n log n)* – piRSquared