Reputation: 209
I want to reshape the following array:
>>> test
array([ 11., 12., 13., 14., 21., 22., 23., 24., 31., 32., 33.,
34., 41., 42., 43., 44.])
in order to obtain:
>>> test2
array([[ 11., 12., 21., 22.],
[ 13., 14., 23., 24.],
[ 31., 32., 41., 42.],
[ 33., 34., 43., 44.]])
I have tried with "reshape" something like
>>> test.reshape(4,4)
array([[ 11., 12., 13., 14.],
[ 21., 22., 23., 24.],
[ 31., 32., 33., 34.],
[ 41., 42., 43., 44.]])
And
>>> test.reshape(2,2,2,2)
array([[[[ 11., 12.],
[ 13., 14.]],
[[ 25., 26.],
[ 27., 28.]]],
[[[ 39., 31.],
[ 32., 33.]],
[[ 41., 44.],
[ 45., 46.]]]])
I have tried different combinations but none works.
Thanks
Upvotes: 3
Views: 511
Reputation: 221744
Approach with reshaping and transposing/swapping axes -
m,n = 2,2 # Block size (rowxcol)
rowlen = 4 # Length of row
out = test.reshape(-1,m,rowlen//n,n).swapaxes(1,2).reshape(-1,rowlen)
# Or transpose(0,2,1,3)
Sample run -
In [104]: test
Out[104]:
array([ 11., 12., 13., 14., 21., 22., 23., 24., 31., 32., 33.,
34., 41., 42., 43., 44.])
In [105]: m,n = 2,2 # Block size (rowxcol)
...: rowlen = 4 # Length of row
...:
In [106]: test.reshape(-1,m,rowlen//n,n).swapaxes(1,2).reshape(-1,rowlen)
Out[106]:
array([[ 11., 12., 21., 22.],
[ 13., 14., 23., 24.],
[ 31., 32., 41., 42.],
[ 33., 34., 43., 44.]])
Upvotes: 5