rambi
rambi

Reputation: 1259

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

Here is my problem :

I’m trying to do a operation on a numpy array after reshaping it.

But after this operation, I want to reshape again my array to get my original shape with the same indexing.

So I want to find the appropriate "inverse reshape" so that 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 ?

I know that the numpy reshape funtion doesn’t copy the array, but the swapaxes one does.

How can I get the appropriate reshaping ?

Upvotes: 0

Views: 863

Answers (1)

hpaulj
hpaulj

Reputation: 231425

Simply reverse the order of the the a=>b conversion.

The original made:

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)

So we need to get b back to the 4d shape, swap the axes back, and reshape to original a shape:

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]])

Upvotes: 2

Related Questions