在NumPy中重塑一个数组

问题描述 投票:33回答:2

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

[[ 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循环,其中将填充数据。我对符合语言的解决方案感兴趣...

python arrays numpy reshape
2个回答
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]]])

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)


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]]])
© www.soinside.com 2019 - 2024. All rights reserved.