Introduction to NumPy and Matplotlib
Chapter 4: Array reshaping
Reshape an array
Mmm… I’m digging that 3D array! Something is still not satisfying enough though!
Mission 4: Get the direction right!
Can you reshape the (3 \times 4) np.array
into a (2 \times 6) np.array
please? But this time, I want you to go by columns. So the first column should say [0, 4]
, the second column should say [-6, 1]
, the third column should be [5, -5]
, etc. I think they used to do that in MATLAB, so I kind of miss that kind of ordering!
x = np.array([[0, 1, 2, 3],
[4, 5, 6, 7],
[-6, -5, -4, -3]
])
reshaped_x = ????
assert np.all(reshaped_x == np.array([[ 0, -6, 5, 2, -4, 7],
[ 4, 1, -5, 6, 3, -3]]))
Hint: Check the possible input arguments for the .reshape()
method.
By default np.array
s are reshaped in row-major order, so left-to-right, top-to-bottom for 2D. You can change this to column-major order (like in MATLAB), so top-to-bottom then left-to-right for 2D. This is done by passing the keyword argument order='F'
(F
stands for Fortran-like order).
reshaped_x = x.reshape((2, 6), order="F")