Chapter 4: Array reshaping

Reshape an array

face Josiah Wang

Excellent, oh young one. You have accomplished your first mission. It gets harder now!

Mission 2: A makeover!

I have a (3 \times 4) np.array, but I need it reshaped it to be a (6 \times 2) np.array instead.

Again, the solution is staring right in front of you in the official documentation. And again, you only need a single statement!

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,  1],
                               [ 2,  3],
                               [ 4,  5],
                               [ 6,  7],
                               [-6, -5],
                               [-4, -3]]))

Again, no peeking until you have tried it!

This one is pretty straightforward, although there are multiple variants to the solutions!

reshaped_x = x.reshape((6, 2))

# This also works
reshaped_x = x.reshape(6, 2)

# You can make one of the dimensions -1. 
# The dimension will be inferred automatically
reshaped_x = x.reshape((-1, 2))
reshaped_x = x.reshape((6, -1))

# There is also a function version if you are not into OOP.
# This only takes a tuple as the second parameter.
reshaped_x = np.reshape(x, (6, 2))

There is also a .resize() method. This is a mutable version of .reshape() which modifies the original array directly.

>>> x = np.array([[0, 1, 2, 3],
...              [4, 5, 6, 7],
...              [-6, -5, -4, -3]
...             ])
...
>>> x.resize((6, 2))
>>> print(x)
[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [-6 -5]
 [-4 -3]]