Jon
Jon

Reputation: 177

How to reshape this array the way I need?

I'm looking to reshape an array of three 2x2 matrices, that is of shape (3,2,2) i.e.

a = np.array([[[a1,a2],[a3,a4]],
             [[b1,b2],[b3,b4]],
             [[c1,c2],[c3,c4]]])

to this array of shape (2,2,3):

[[[a1,b1,c1],[a2,b2,c2]],
 [[a3,b3,c3],[a4,b4,c4]]])

The regular np.reshape(a, (2,2,3)) returns this array:

[[[a1, a2, a3],[a4, b1, b2]],
 [[b3, b4, c1],[c2, c3, c4]]]

and np.reshape(a, (2,2,3), order = 'F') brings this:

[[[a1, b3, c2],[c1, a2, b4]],
 [[b1, c3, a4],[a3, b2, c4]]]

How can I reshape the initial array to get what I need?

This is in order to use with matplotlib.pyplot.imshow where the three initial matrices correspond to the three colors 'RGB' and each of the elements is a float in the range [0,1]. So also if there's a better way to do it I would be happy to know.

Upvotes: 3

Views: 87

Answers (2)

Divakar
Divakar

Reputation: 221614

We simply need to permute axes. Two ways to do so.

Use np.transpose -

a.transpose(1,2,0) # a is input array
# or np.transpose(a,(1,2,0))

We can also use np.moveaxis -

np.moveaxis(a,0,2)    # np.moveaxis(a, 0, -1)

Sample run -

In [157]: np.random.seed(0)

In [158]: a = np.random.randint(11,99,(3,2,2))

In [159]: a
Out[159]: 
array([[[55, 58],
        [75, 78]],

       [[78, 20],
        [94, 32]],

       [[47, 98],
        [81, 23]]])

In [160]: a.transpose(1,2,0)
Out[160]: 
array([[[55, 78, 47],
        [58, 20, 98]],

       [[75, 94, 81],
        [78, 32, 23]]])

Upvotes: 2

gmds
gmds

Reputation: 19885

What you want is the transpose:

a = np.array([[['a1', 'a2'],['a3', 'a4']],
             [['b1', 'b2'],['b3', 'b4']],
             [['c1', 'c2'],['c3', 'c4']]])

print(np.rollaxis(a, 1, 3).T)

Output:

[[['a1' 'b1' 'c1']
  ['a2' 'b2' 'c2']]

 [['a3' 'b3' 'c3']
  ['a4' 'b4' 'c4']]]

Upvotes: 1

Related Questions