【问题标题】:Reshape an array in NumPy在 NumPy 中重塑数组
【发布时间】:2013-01-06 17:42:04
【问题描述】:

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

[[ 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


    【解决方案1】:
    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]]])
    

    【讨论】:

    • 请注意,b 现在不是连续的,这意味着它不能就地重新整形:b.reshape(9, 2) 返回一个副本,而不是相同数据的视图,b.shape = (9, 2) 将引发错误.
    • @Jaime 的非常重要的评论,因为 Shape 的重点是允许在没有克隆的情况下乐观地调整大小。处理大量数据集
    • 为什么需要换轴?
    【解决方案2】:

    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)

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        • 2020-07-11
        • 1970-01-01
        • 2011-10-01
        • 2018-04-13
        • 2019-05-05
        • 1970-01-01
        相关资源
        最近更新 更多