44

考虑以下形式的数组(只是一个示例):

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

4

3 回答 3

69
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]]])
于 2013-01-23T09:37:31.433 回答
1

numpy 有一个很好的工具来完成这个任务(“numpy.reshape”)链接到 reshape 文档

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)

于 2019-04-25T11:35:53.503 回答
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]]])
于 2019-07-01T00:13:46.860 回答