简体   繁体   English

置换numpy的二维数组索引

[英]Permuting numpy's 2d array indexes

are there any numpy function or clever use of views to accomplish what the following function do? 是否有任何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

That is, for a given permutation of the indexes of the matrix in a list perm , this function calculates the result of applying this permutation to the indexes of a matrix. 也就是说,对于列表perm矩阵索引的给定排列,此函数计算将此排列应用于矩阵的索引的结果。

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

Actually, this is better as it does it in a single go: 实际上,这样做更好,因为它可以一次完成:

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

To work with non-square arrays: 要使用非平方数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM