Python Forum

Full Version: Reshaping matrix
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All

I'm wondering how to reshape the matrix A so that it equals B?

My issue is the row order; I spent a long time playing with tranpose, ravel, reshape + order, and so on, but I've not found the tock so far.

What I'm missing?

Of course using Permutation works fine in that simple example, but is there another way?

Thanks for any help

Paul

A = np.array( [[0, 0, 0, 1, 1, 1, 2, 2, 2],
               [1, 2, 5, 4, 7, 8, 9, 10, 11]])

#expected
B = np.array( [[0, 0, 0],
               [1, 2, 5],
               [1, 1, 1],
               [4, 7, 8],
               [2, 2, 2],
               [9, 10, 11]])

A2 = np.reshape(A, (6, 3)) # dimension is correct but not row order
Permutation = [0, 3, 1, 4, 2, 5]
A3 = A2[Permutation, :]

Diff = B - A3
print(Diff)
There must be better ways but first what comes in mind is split, stack and then reshape:

>>> arr = np.array( [[0, 0, 0, 1, 1, 1, 2, 2, 2],
...                 [1, 2, 5, 4, 7, 8, 9, 10, 11]])
>>> arr
array([[ 0,  0,  0,  1,  1,  1,  2,  2,  2], 
       [ 1,  2,  5,  4,  7,  8,  9, 10, 11]])
>>> np.split(arr[0], 3)                                               # split row
[array([0, 0, 0]), array([1, 1, 1]), array([2, 2, 2])]
>>> np.hstack((np.split(m[0], 3), np.split(m[1], 3)))                 # split rows and stack horizontally
array([[ 0,  0,  0,  1,  2,  5], 
       [ 1,  1,  1,  4,  7,  8],
       [ 2,  2,  2,  9, 10, 11]])
>>> np.hstack((np.split(m[0], 3), np.split(m[1], 3))).reshape(6,3)   # split rows, stack, reshape
array([[ 0,  0,  0],
       [ 1,  2,  5],
       [ 1,  1,  1],
       [ 4,  7,  8],
       [ 2,  2,  2],
       [ 9, 10, 11]])
Thanks for the answer

I understand what you did; maybe not the easiest way as you said Wink

I need to reflect on it