Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reshaping matrix
#1
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)
Reply
#2
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]])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Thanks for the answer

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

I need to reflect on it
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  reshaping 2D numpy array paul18fr 3 1,024 Jan-03-2023, 06:45 PM
Last Post: paul18fr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020