2012-08-24 120 views
0

是否有任何numpy函数或巧妙使用视图来完成以下函数的功能?排列numpy的2d数组索引

import numpy as np 

def permuteIndexes(array, perm): 
    newarray = np.empty_like(array) 
    max_i, max_j = newarray.shape 
    for i in xrange(max_i): 
     for j in xrange(max_j): 
      newarray[i,j] = array[perm[i], perm[j]] 
    return newarray 

即,对于矩阵的列表中的perm索引的一个给定的排列,该函数计算应用这种排列,以矩阵的索引的结果。

回答

6
def permutateIndexes(array, perm): 
    return array[perm][:, perm] 

其实,这是更好,因为它是在一个单一的去:

def permutateIndexes(array, perm): 
    return array[np.ix_(perm, perm)] 

同非方阵工作:

def permutateIndexes(array, perm): 
    return array[np.ix_(*(perm[:s] for s in array.shape))] 
+0

hummm!我必须学习如何正确使用这些观点。有没有任何指导? –

+1

@ RafaelS.Calsaverini如果你还没有阅读[Tentative NumPy Tutorial](http://www.scipy.org/Tentative_NumPy_Tutorial),请务必阅读。 – ecatmur