置换numpy的2d数组索引

Raf*_*ini 0 python arrays numpy multidimensional-array

是否有任何numpy功能或巧妙地使用视图来完成以下功能?

 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
Run Code Online (Sandbox Code Playgroud)

也就是说,对于列表中矩阵的索引的给定排列perm,该函数计算将该置换应用于矩阵的索引的结果.

eca*_*mur 6

def permutateIndexes(array, perm):
    return array[perm][:, perm]
Run Code Online (Sandbox Code Playgroud)

实际上,这更好,因为它一次性完成:

def permutateIndexes(array, perm):
    return array[np.ix_(perm, perm)]
Run Code Online (Sandbox Code Playgroud)

要使用非正方形数组:

def permutateIndexes(array, perm):
    return array[np.ix_(*(perm[:s] for s in array.shape))]
Run Code Online (Sandbox Code Playgroud)