【问题标题】:Numpy reshaping 2D to 3D: moving columns to "depth"Numpy 将 2D 重塑为 3D:将列移动到“深度”
【发布时间】:2019-08-19 03:19:29
【问题描述】:

问题

如何将 2D 矩阵重塑为 3D 矩阵,其中列“深度”移动?

我希望数组 a 看起来像数组 b

import numpy as np

a = np.array([
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
            ])

b = np.array([
                [[1,1,1,1,1,1], 
                 [1,1,1,1,1,1], 
                 [1,1,1,1,1,1], 
                 [1,1,1,1,1,1]],
                [[2,2,2,2,2,2], 
                 [2,2,2,2,2,2], 
                 [2,2,2,2,2,2], 
                 [2,2,2,2,2,2]],
                [[3,3,3,3,3,3], 
                 [3,3,3,3,3,3], 
                 [3,3,3,3,3,3], 
                 [3,3,3,3,3,3]],
            ])

我想做什么

结果不是我想要达到的结果

x = np.reshape(a, (a.shape[0], -1, 3))

我还尝试了以下方法: 1) hsplit a 成 3 组 2) 尝试 dstack 这些集合但没有产生想要的结果

b = np.hsplit(a,3)
c = np.dstack([b[0],b[1],b[2]])

【问题讨论】:

    标签: python numpy 3d 2d reshape


    【解决方案1】:

    应该这样做:

    import numpy as np
    
    a = np.array([
                    [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                    [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                    [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                    [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
                ])
    
    b = np.array([
                    [[1,1,1,1,1,1],
                     [1,1,1,1,1,1],
                     [1,1,1,1,1,1],
                     [1,1,1,1,1,1]],
                    [[2,2,2,2,2,2],
                     [2,2,2,2,2,2],
                     [2,2,2,2,2,2],
                     [2,2,2,2,2,2]],
                    [[3,3,3,3,3,3],
                     [3,3,3,3,3,3],
                     [3,3,3,3,3,3],
                     [3,3,3,3,3,3]],
                ])
    
    a_new = np.swapaxes(a.reshape(a.shape[0], 3, -1), 0, 1)
    
    np.array_equal(a_new, b)
    

    -> 是的

    【讨论】:

      【解决方案2】:

      您只需要transpose,即Treshape

      a.T.reshape(3,4,6)
      

      a.T.reshape(b.shape)
      
      Out[246]:
      array([[[1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1]],
      
             [[2, 2, 2, 2, 2, 2],
              [2, 2, 2, 2, 2, 2],
              [2, 2, 2, 2, 2, 2],
              [2, 2, 2, 2, 2, 2]],
      
             [[3, 3, 3, 3, 3, 3],
              [3, 3, 3, 3, 3, 3],
              [3, 3, 3, 3, 3, 3],
              [3, 3, 3, 3, 3, 3]]])
      

      【讨论】:

        猜你喜欢
        • 2019-09-12
        • 1970-01-01
        • 2017-09-18
        • 2015-10-19
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多