重塑 numpy 数组,进行转换并进行反向重塑

reshape numpy array, do a transformation and do the inverse reshape

这是我的问题:

我正在尝试对 numpy 数组进行重塑后的操作。

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

所以我想找到合适的 "inverse reshape" 以便 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 会。

我怎样才能得到合适的整形?

简单地颠倒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]])