2016-04-27 69 views
0

所以,我有這個矩陣是M=60x8使用索引數組在Python中進行索引

然後,我找到每行使用此z= M.argmax(axis=1) 因此z is a 60 element array最大元素包含索引從0-7。

除了循環迭代的老式方法之外,我可以在python中使用某種矢量化代碼,以便使用z矩陣打印M的值,在此處獲得最大值。

+0

您正在尋找[numpy的(http://www.numpy.org/)。特別是,[numpy.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) –

回答

0
import numpy as np 

# define our matrix M 
M = np.arange(6*8).reshape(6,8) 

當我們看於嘉:

> M 
> array(
    [[ 0, 1, 2, 3, 4, 5, 6, 7], 
    [ 8, 9, 10, 11, 12, 13, 14, 15], 
    [16, 17, 18, 19, 20, 21, 22, 23], 
    [24, 25, 26, 27, 28, 29, 30, 31], 
    [32, 33, 34, 35, 36, 37, 38, 39], 
    [40, 41, 42, 43, 44, 45, 46, 47]]) 

> M.shape 
> (6, 8) 

現在,我們每行的最大ARG:

> z = np.argmax(M, axis=1) 
> array([7, 7, 7, 7, 7, 7]) 

因此,我們得到了每一個最大元素的索引行。如果我們想取回值,我們可以簡單地通過併購片:

> M[np.arange(M.shape[0]), z] 
> array([ 7, 15, 23, 31, 39, 47]) 

np.arange(M.shape[0])爲每一列建立索引,而z涵蓋列的索引。因此,我們正在提取每行的第n個元素(根據z的條目)。


爲了證明這適用於任意的 「排序」 數組:

> M2 = np.ravel(np.copy(M)) 
> np.random.shuffle(M2) 
> M2 = M2.reshape(M.shape[0], M.shape[1]) 
> M2 
> array(
    [[34, 16, 5, 32, 31, 2, 17, 38], 
    [33, 18, 9, 46, 20, 4, 39, 30], 
    [10, 41, 35, 23, 0, 24, 45, 14], 
    [28, 36, 8, 22, 11, 15, 7, 44], 
    [27, 1, 25, 6, 3, 19, 47, 37], 
    [40, 42, 29, 21, 12, 43, 26, 13]]) 

> z2 = np.argmax(M2, axis=1) 
> array([7, 3, 6, 7, 6, 5]) 

> M2[np.arange(M2.shape[0]), z2] 
> array([38, 46, 45, 44, 47, 43])