重整numpy数组,进行变换并进行逆整形

问题描述 投票:0回答:1

这是我的问题:

我想在对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重塑功能不会复制数组,但是交换轴会复制数组。

如何获得适当的重塑?

numpy multidimensional-array reshape
1个回答
0
投票

简单地反转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]])
© www.soinside.com 2019 - 2024. All rights reserved.