Chapter 5 · Part 2

Reshaping & combining

The same numbers can wear many shapes. Reshaping rearranges an array's dimensions without changing its data, and combining glues arrays together. Both come up constantly — flattening an image for a network, stacking features into a matrix, batching data.

Reshape and transpose

reshape gives an array new dimensions, as long as the total element count matches. Pass -1 for one dimension and NumPy figures it out for you:

reshape.py
r = np.arange(12)            # [0 1 2 ... 11], shape (12,)

r.reshape(3, 4)              # 3 rows, 4 columns
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

r.reshape(3, -1)            # same thing — NumPy computes the 4
r.reshape(3, 4).reshape(-1) # flatten back to 1-D

Transpose (.T) flips rows and columns — a (3, 4) becomes a (4, 3):

a = np.arange(12).reshape(3, 4)
a.T          # shape (4, 3): rows become columns

Combining arrays

Stack arrays into bigger ones. The common trio:

combine.py
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])

np.vstack([A, B])        # stack as rows        -> [[1 2 3]
                       #                          [4 5 6]]
np.column_stack([A, B])  # stack as columns     -> [[1 4]
                       #                          [2 5]
                       #                          [3 6]]
np.concatenate([A, B])   # join end to end      -> [1 2 3 4 5 6]
🎯 Your turn
Build a 4×4 checkerboard of 0s and 1s (a 1 in the top-left corner), using slicing with a step. Hint: start from np.zeros((4,4), dtype=int) and assign 1 to two striped slices.

You've got the full toolkit. Time to put every piece together on something fun.