在数组中转置数组

时间:2014-04-25 12:17:57

标签: python numpy

我有一个形状(M*N,N)的二维数组,实际上由MN*N数组组成。我想以矢量化方式转置所有这些元素(N*N矩阵)。例如,

import numpy as np
A=np.arange(1,28).reshape((9,3))
print "A before transposing:\n", A
for i in range(3):
    A[i*3:(i+1)*3,:]=A[i*3:(i+1)*3,:].T
print "A after transposing:\n", A

此代码生成以下输出:

A before transposing: 
[[ 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]]
A after transposing: 
 [[ 1  4  7]
 [ 2  5  8]
 [ 3  6  9]
 [10 13 16]
 [11 14 17]
 [12 15 18]
 [19 22 25]
 [20 23 26]
 [21 24 27]]

我期待的。但我想要矢量化版本。

2 个答案:

答案 0 :(得分:8)

这是一种令人讨厌的方法,可以在一行中完成!

A.reshape((-1, 3, 3)).swapaxes(-1, 1).reshape(A.shape)

一步一步。重塑为(3, 3, 3)

>>> A.reshape((-1, 3, 3))
array([[[ 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]]])

然后在每个子阵列上执行类似转置的操作swapaxes

>>> A.reshape((-1, 3, 3)).swapaxes(-1, 1)
array([[[ 1,  4,  7],
        [ 2,  5,  8],
        [ 3,  6,  9]],

       [[10, 13, 16],
        [11, 14, 17],
        [12, 15, 18]],

       [[19, 22, 25],
        [20, 23, 26],
        [21, 24, 27]]])

最后重塑为(9, 3)

>>> A.reshape((-1, 3, 3)).swapaxes(-1, 1).reshape(A.shape)
array([[ 1,  4,  7],
       [ 2,  5,  8],
       [ 3,  6,  9],
       [10, 13, 16],
       [11, 14, 17],
       [12, 15, 18],
       [19, 22, 25],
       [20, 23, 26],
       [21, 24, 27]])
>>> 

我认为,对于任何方法,必须复制数据,因为没有可以从以下结果生成结果的2d步幅/形状:

array([ 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])

(是吗?)在我的版本中,我认为数据会在最终的重塑步骤中被复制

答案 1 :(得分:3)

In [42]: x = np.arange(1,28).reshape((9,3))

In [43]: x
Out[43]: 
array([[ 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]])


In [31]: r,c = x.shape
In [39]: z = np.vstack(np.hsplit(x.T,r/c))

In [45]: z
Out[45]: 
array([[ 1,  4,  7],
       [ 2,  5,  8],
       [ 3,  6,  9],
       [10, 13, 16],
       [11, 14, 17],
       [12, 15, 18],
       [19, 22, 25],
       [20, 23, 26],
       [21, 24, 27]])