【问题标题】:reshape numpy array, do a transformation and do the inverse reshape重塑 numpy 数组,进行转换并进行反向重塑
【发布时间】:2020-07-17 08:16:49
【问题描述】:

这是我的问题:

我正在尝试在整形后对一个 numpy 数组进行操作。

但是在这个操作之后,我想再次重塑我的数组以获得具有相同索引的原始形状。

所以我想找到合适的“反向重塑”,以便 inverse_reshape(reshape(a))==a

length = 10
a = np.arange(length^2).reshape((length,length))
#a.spape = (10,10)


b = (a.reshape((length//2, 2, -1, 2))
     .swapaxes(1, 2)
     .reshape(-1, 2, 2))

#b.shape = (25,2,2)


b = my_function(b)
#b.shape = (25,2,2)    still the same shape

# b --> a ?

我知道 numpy reshape 函数不会复制数组,但 swapaxes 会。

我怎样才能得到适当的重塑?

【问题讨论】:

    标签: numpy multidimensional-array reshape


    【解决方案1】:

    只需颠倒a=>b 转换的顺序。

    原作:

    In [53]: a.reshape((length//2, 2, -1, 2)).shape                                                
    Out[53]: (5, 2, 5, 2)
    In [54]: a.reshape((length//2, 2, -1, 2)).swapaxes(1,2).shape                                  
    Out[54]: (5, 5, 2, 2)
    In [55]: b.shape                                                                               
    Out[55]: (25, 2, 2)
    

    所以我们需要将b 恢复为 4d 形状,将轴交换回来,然后重新调整为原始 a 形状:

    In [56]: b.reshape(5,5,2,2).swapaxes(1,2).reshape(10,10)                                       
    Out[56]: 
    array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
           [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
           [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
           [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
           [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
           [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
           [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
           [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 2016-02-10
      • 2019-01-09
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多