All articles

Reshaping and Combining NumPy Arrays: reshape, Axes, Stack and Split

Change array shapes, understand axis 0 and axis 1, and join and split arrays, including images and batches.

0 · log in to like, save & follow Share on LinkedIn Share on X

Data rarely arrives in the shape you need. A sensor gives you one long list of readings that you want as days × hours; two months of sales need to be joined into one table; a model wants a column, but you have a row. This fifth part of our NumPy Fundamentals series is about changing an array's shape and joining and splitting arrays, and along the way it finally makes sense of axes, the idea behind almost every axis= argument in NumPy.

Reshaping and Combining NumPy Arrays: reshape, Axes, Stack and Split

reshape: same data, new shape

reshape arranges the same elements into a different shape. The total number of elements must stay the same:

import numpy as np

a = np.arange(12)
m = a.reshape(3, 4)
print(m)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Twelve values become 3 rows of 4. NumPy fills the new shape row by row, in the same order as the original. Like a slice (see views vs copies), reshape usually returns a view of the same data rather than copying it, so it is cheap even for huge arrays.

You can leave one dimension as -1 and NumPy works it out for you:

print(a.reshape(2, -1).shape)
(2, 6)

This is handy when you know the number of rows but would rather not calculate the columns yourself. If the numbers do not divide evenly, NumPy says so:

try:
    np.arange(10).reshape(3, 4)
except ValueError as e:
    print("ValueError:", e)
ValueError: cannot reshape array of size 10 into shape (3,4)

Transpose and flatten

.T swaps rows and columns, which is called transposing:

print(m.T)
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]

Going the other way, ravel flattens any array back into one dimension:

print(m.ravel())
[ 0  1  2  3  4  5  6  7  8  9 10 11]

Understanding axes

An axis is one dimension of an array. In a 2D array, axis 0 runs down the rows and axis 1 runs across the columns. When a function takes axis=0, it works down each column and collapses the rows; with axis=1 it works across each row and collapses the columns:

print(m.sum(axis=0), m.sum(axis=1))   # per column, per row
[12 15 18 21] [ 6 22 38]

A memory aid: the axis you name is the one that disappears. Summing a (3, 4) array over axis=0 removes the 3 and leaves 4 column totals. You will use this constantly in Part 6, where we calculate means and maximums per row and per column.

Adding a dimension with np.newaxis

Sometimes you need a 1D array as an explicit column or row, for example to make broadcasting line up. np.newaxis inserts a dimension of size 1:

x = np.array([1, 2, 3])
print(x[:, np.newaxis].shape, x[np.newaxis, :].shape)
(3, 1) (1, 3)

x[:, np.newaxis] turns the values into a column; x[np.newaxis, :] makes a single row. x.reshape(-1, 1) does the same as the first, so use whichever reads better to you.

Joining arrays

To combine arrays, use np.concatenate along an existing axis. Remember from Part 1 that + adds arrays rather than joining them, the opposite of how + works on lists:

p = np.array([[1, 2], [3, 4]])
q = np.array([[5, 6], [7, 8]])
print(np.concatenate([p, q]))          # axis=0: stack rows
print(np.concatenate([p, q], axis=1))  # axis=1: side by side
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[[1 2 5 6]
 [3 4 7 8]]

The shortcuts vstack and hstack read more naturally, and np.stack creates a new axis instead of extending an existing one:

print(np.vstack([p, q]).shape, np.hstack([p, q]).shape, np.stack([p, q]).shape)
(4, 2) (2, 4) (2, 2, 2)

stack is what you want when, say, you have one 2D table per month and want a 3D array of months × rows × columns.

Splitting arrays

np.split is the reverse of joining. Give it the number of equal parts:

parts = np.split(np.arange(9), 3)
print(parts)
left, right = np.hsplit(np.arange(8).reshape(2, 4), 2)
print(left)
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
[[0 1]
 [4 5]]

Splitting is common when dividing data into training and test sets, or into one chunk per worker.

Terminal output of the reshaping and joining examples

Reshaping in the real world: images and batches

Reshaping matters most when data has more than two dimensions. Machine-learning code often handles a batch of images as a 4D array: number of images × height × width × channels. Many classic models want each image as one long row instead, so the batch is flattened with reshape(n, -1):

batch = np.arange(2 * 2 * 3 * 3).reshape(2, 2, 3, 3)   # 2 tiny images, 2x3 pixels, 3 channels
print(batch.shape, batch.reshape(2, -1).shape)
(2, 2, 3, 3) (2, 18)

Each image becomes a row of 18 values (2 × 3 × 3), and the -1 saves us working that out.

Different libraries also order the axes differently: some put the colour channel last (height, width, channels) and some first (channels, height, width). transpose reorders axes by listing the old axis numbers in their new order:

rgb = np.arange(12).reshape(2, 2, 3)        # height x width x channels
print(rgb.transpose(2, 0, 1).shape)         # channels x height x width
print(rgb.mean(axis=2).round(1))            # average the channels: greyscale
(3, 2, 2)
[[ 1.  4.]
 [ 7. 10.]]

Averaging over axis=2, the channel axis, collapses the three colours into one value per pixel, a simple greyscale conversion. It is the same "the named axis disappears" rule as before, just in three dimensions. When you hit a shape error in a real project, printing .shape and asking which axis is which almost always finds the bug.

Practice exercises

  1. Turn the 14 daily step counts np.arange(1, 15) into two weeks of seven days, one row per week.
  2. Total each week.
  3. Put the arrays [1, 2, 3] and [4, 5, 6] side by side as two columns.
  4. What is the shape of np.arange(6).reshape(2, 3).T? Predict it, then check.
week = np.arange(1, 15)
print(week.reshape(2, 7))
print(week.reshape(2, 7).sum(axis=1))

a = np.array([1, 2, 3]); b = np.array([4, 5, 6])
print(np.column_stack([a, b]))
print(np.arange(6).reshape(2, 3).T.shape)
[[ 1  2  3  4  5  6  7]
 [ 8  9 10 11 12 13 14]]
[28 77]
[[1 4]
 [2 5]
 [3 6]]
(3, 2)

np.column_stack is the easy way to turn several 1D arrays into the columns of a table; we use it to build a report in the project. Transposing a (2, 3) array always gives (3, 2).

Common mistakes

  • Mixing up the axes. Axis 0 is down the rows, axis 1 is across the columns; the named axis is the one that disappears.
  • Reshaping to an impossible shape. The product of the new dimensions must equal size. Use -1 to let NumPy calculate one of them.
  • Using + to join arrays. It adds them element by element. Use concatenate, vstack or hstack.
  • Concatenating arrays whose other dimensions differ. To stack rows, every array needs the same number of columns.

Wrapping up

You can now reshape and transpose arrays, reason about axes, add dimensions for broadcasting, and join and split arrays. Next, in Aggregations and Statistics, we put axes to work: totals, averages, extremes, sorting, counting and dealing with missing values.

Enjoyed this article? Get the best GeeksArray articles in your inbox — once a week, no spam, unsubscribe anytime.

Comments (0)

Log in to join the conversation.

No comments yet — be the first to share your thoughts.