在NumPy中重塑数组

2024-10-19 16:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下形式的数组(仅举一个例子):

[[ 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循环。我感兴趣的解决方案是语言一致性。。。


Tags: 数据语言for地方数组解决方案pythonic感兴趣
3条回答

对于这个任务,numpy有一个很好的工具(“numpy.reforme”)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)

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]]])

有两种可能的结果重新排列(以下是@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]]])

相关问题 更多 >