排列矩阵的行和列

问题描述:

假设我具有以下矩阵/数组:

Assuming that I have the following matrix/array:

array([[0, 0, 1, 1, 1],
       [0, 0, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 0, 1, 0, 0],
       [1, 1, 1, 0, 0]])

并且我想应用以下排列:

and I want to apply the following permutation:

1 -> 5
2 -> 4

结果应该在最后:

array([[1, 1, 1, 0, 0],
       [1, 0, 1, 0, 0],
       [1, 1, 0, 1, 1],
       [0, 0, 1, 0, 1],
       [0, 0, 1, 1, 1]])

现在,一种非常幼稚(且耗费内存)的方式可能是:

Now, an incredibly naive (and memory costly) way of doing so might be:

a2 = deepcopy(a1)
a2[0,:] = a1[4,:]
a2[4,:] = a1[0,:]
a = deepcopy(a2)
a2[:,0] = a[:,4]
a2[:,4] = a[:,0]

a3 = deepcopy(a2)
a2[1,:] = a3[3,:]
a2[3,:] = a3[1,:]
a = deepcopy(a2)
a2[:,1] = a[:,3]
a2[:,3] = a[:,1]

但是,我想知道是否有更有效的方法可以做到这一点. numpy.shuffle和numpy.permutation似乎仅置换矩阵的行(而不同时置换列).这对我来说不起作用,因为矩阵是邻接矩阵(表示图),并且我需要进行置换,这将使我得到一个与原始图同构的图.此外,我需要进行任意数量的排列(不止一个).

But, I would like to know if there is something more efficient that does this. numpy.shuffle and numpy.permutation seem to permute only the rows of the matrix (not the columns at the same time). That doesn't work for me because the matrices are adjacency matrices (representing graphs), and I need to do the permutations which will give me a graph which is isomorphic with the original graph. Furthermore, I need to do an arbitrary number of permutations (more than one).

谢谢!

您可以使用请注意,数组索引总是返回副本而不是视图-不能在不生成副本的情况下交换数组的任意行/列.

Note that array indexing always returns a copy rather than a view - there's no way to swap arbitrary rows/columns of an array without generating a copy.

在这种特殊情况下,您可以通过使用切片索引来避免复制,该索引将返回视图而不是副本:

In this particular case you could avoid the copy by using slice indexing, which returns a view rather than a copy:

b = b[::-1] # invert the row order

print(repr(b))
# array([[1, 1, 1, 0, 0],
#        [1, 0, 1, 0, 0],
#        [1, 1, 0, 1, 1],
#        [0, 0, 1, 0, 1],
#        [0, 0, 1, 1, 1]])


更新:

您可以使用相同的索引编制方法来交换列.


Update:

You can use the same indexing approach to swap columns.

c = np.arange(25).reshape(5, 5)
print(repr(c))
# 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]])

c[[0, 4], :] = c[[4, 0], :]     # swap row 0 with row 4...
c[:, [0, 4]] = c[:, [4, 0]]     # ...and column 0 with column 4

print(repr(c))

# array([[24, 21, 22, 23, 20],
#        [ 9,  6,  7,  8,  5],
#        [14, 11, 12, 13, 10],
#        [19, 16, 17, 18, 15],
#        [ 4,  1,  2,  3,  0]])

在这种情况下,我使用了一个不同的示例数组-执行行/列交换后,您的版本将产生相同的输出,这使得很难理解发生了什么.

I've used a different example array in this case - your version will yield an identical output after performing the row/column swaps which makes it difficult to understand what's going on.