将方形数组的 Numpy 数组转换为 numpy 方形数组,从而节省"layout"



我第一次在这里问一些事情。我有点"被封锁"。

我有一个由 n x n 个数组组成的数组(为了简化起见,让我们取 n=3(:

[
    [
        [ 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, 25, 26]
    ]
        ]

(虽然我的数组包含的数组远远超过 3 个 3*3 数组(

我想实现这样的 2D 数组:

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

有没有一个技巧我没有想到,因为我想不出任何方法来完成转换。

谢谢

也许比moveaxis稍微干净一些:

import numpy as np
a = np.arange(27).reshape(3,3,3)
a.swapaxes(0,1).reshape(3,-1)
array([[ 0,  1,  2,  9, 10, 11, 18, 19, 20],
   [ 3,  4,  5, 12, 13, 14, 21, 22, 23],
   [ 6,  7,  8, 15, 16, 17, 24, 25, 26]])

将其视为要水平连接的 3 个数组的列表:

In [171]: arr = np.arange(27).reshape(3,3,3)
In [172]: np.hstack(arr)
Out[172]: 
array([[ 0,  1,  2,  9, 10, 11, 18, 19, 20],
       [ 3,  4,  5, 12, 13, 14, 21, 22, 23],
       [ 6,  7,  8, 15, 16, 17, 24, 25, 26]])
In [173]: arr
Out[173]: 
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, 25, 26]]])

我喜欢用不同维度的数组测试想法。 然后各种轴操作变得更加明显。

In [174]: arr = np.arange(24).reshape(2,3,4)
In [175]: arr
Out[175]: 
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]]])
In [176]: np.hstack(arr)
Out[176]: 
array([[ 0,  1,  2,  3, 12, 13, 14, 15],
       [ 4,  5,  6,  7, 16, 17, 18, 19],
       [ 8,  9, 10, 11, 20, 21, 22, 23]])
In [177]: np.vstack(arr)
Out[177]: 
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]])

但是,如果从 3D 数组(而不是数组列表(开始,转置和重塑答案的变化并没有错:

In [187]: arr.transpose(1,0,2).reshape(3,-1)
Out[187]: 
array([[ 0,  1,  2,  9, 10, 11, 18, 19, 20],
       [ 3,  4,  5, 12, 13, 14, 21, 22, 23],
       [ 6,  7,  8, 15, 16, 17, 24, 25, 26]])

您可以使用np.block

>>> import numpy as np
>>> X = np.arange(27).reshape(3, 3, 3)
>>> 
>>> np.block(list(X))
array([[ 0,  1,  2,  9, 10, 11, 18, 19, 20],
       [ 3,  4,  5, 12, 13, 14, 21, 22, 23],
       [ 6,  7,  8, 15, 16, 17, 24, 25, 26]])

简单的整形是不够的,因为您必须先更改轴的顺序:

import numpy as np
a = np.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,25,26]]])
np.moveaxis(a, 0, 1).reshape(3,9)
[[ 0  1  2  9 10 11 18 19 20]
 [ 3  4  5 12 13 14 21 22 23]
 [ 6  7  8 15 16 17 24 25 26]]

最新更新