How to understand B=np.reshape(A, (a, a, b)) and reverse back by B[:,:,1]

Question:

I am quite confused about the following

import numpy as np
A = np.array([[1,2,3],
              [2,3,4],
              [3,4,5]])

A is a 3×3 matrix obviously. Now consider

B = np.reshape(A, (3, 3, 1))

B is

array([[[1],
    [2],
    [3]],

   [[2],
    [3],
    [4]],

   [[3],
    [4],
    [5]]])

If I want to get A back, just simply do

C = B[:,:,0]

I am quite confused the trick behind it to get B and C.

Asked By: Denny

||

Answers:

reshape takes the numbers from the array in order as a single list of numbers, and reorganizes it to the new shape. It is quite efficient, because it doesn’t have to change the array at all — just the interpretation. In this case, three sets of three rows of one column each.

[:,:,0] means "take all of the first dimension [3], and all of the second dimension [3] and delete the third dimension", thus taking you back to a 3×3. Again, that’s just changing the interpretation of the same list of 9 numbers.

Answered By: Tim Roberts
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.