在NumPy中重塑一个数组

时间:2013-01-23 09:35:21

标签: python arrays numpy reshape

考虑以下形式的数组(仅作为示例):

[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

它的形状是[9,2]。现在我想转换数组,使每列成为一个形状[3,3],如下所示:

[[ 0  6 12]
 [ 2  8 14]
 [ 4 10 16]]
[[ 1  7 13]
 [ 3  9 15]
 [ 5 11 17]]

最明显的(当然也是“非pythonic”)解决方案是使用适当的维度初始化一个零数组,并运行两个for循环,其中将填充数据。我对符合语言的解决方案感兴趣...

3 个答案:

答案 0 :(得分:55)

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

答案 1 :(得分:0)

numpy具有完成此任务的出色工具(“ numpy.reshape”)link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

您还可以使用“ -1”技巧

`a = a.reshape(-1,3)`

“-1”是通配符,当第二维为3时,将使numpy算法决定要输入的数字

是的,这也可以:      a = a.reshape(3,-1)

:     a = a.reshape(-1,2) 什么都不做

:     a = a.reshape(-1,9) 会将形状更改为(2,9)

答案 2 :(得分:0)

有两种可能的结果重排(以下为@eumiro的示例)。 Einops程序包提供了一种功能强大的注释,可以清楚地描述此类操作

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])