Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 49 ยท Shapes and Combining

Reshaping Arrays

Change the shape of NumPy arrays without copying data. Learn reshape with -1, ravel vs flatten, transpose, moveaxis, squeeze, expand_dims and C vs F order.

An array is two things: a flat block of numbers in memory, and a shape that tells NumPy how to read that block as rows, columns and deeper dimensions. Reshaping changes only the second part. The numbers stay where they are, so reshaping is usually instant, even for huge arrays.

Almost every real NumPy program reshapes constantly: turning a long vector into an image grid, adding an axis so two arrays broadcast together, flattening a batch before a calculation, or putting the color channel first. This lesson covers all the tools, the difference between views and copies when reshaping, and a first look at strides, the numbers that make it all work.

reshape: same data, new shape

a.reshape(rows, cols) (or np.reshape(a, shape)) returns an array with the new shape. The only rule is that the total number of elements must stay the same: 3 * 4 == 12.

flowchart LR
    A["flat memory<br/>0 1 2 3 4 5 6 7 8 9 10 11"] --> B["shape (3, 4)<br/>3 rows of 4"]
    A --> C["shape (2, 6)<br/>2 rows of 6"]
    A --> D["shape (2, 2, 3)<br/>2 blocks of 2x3"]

One block of 12 numbers can be read through many different shapes.

You may use -1 for one dimension and let NumPy work it out. That is how you write "as many rows as needed, 6 columns" without doing the division yourself.

Python reshape and the -1 shortcut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two important points from that output:

  • A wrong total size raises ValueError. The message names both the size you have and the shape you asked for.
  • reshape normally returns a view: b and a share the same memory, so writing 99 through b changed a. This is cheap and usually what you want, but never forget it when you modify the result. Views vs Copies explores the topic in depth. When you need an independent array, call .copy().

By default, numbers are read and written in row-major (C) order: the last index changes fastest, so a row is filled before the next row starts. You can change that with order="F", covered below.

ravel and flatten

To collapse an array to one dimension you have two choices that look the same but differ in one important way:

  • a.ravel() returns a flattened array and tries to return a view. It only copies when it must.
  • a.flatten() always returns a copy.
Python ravel versus flatten

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Changing the ravel() result changed m, while changing the flatten() result did not. The last line shows the catch: for the transposed array t, a flat view in row-major order is impossible (the elements are not laid out in that order in memory), so ravel silently made a copy. If your code depends on sharing or on isolation, say so explicitly: use .reshape(-1) or .ravel() for "view if possible", and .flatten() or .copy() for "definitely independent".

Warning: Because ravel and reshape may or may not copy depending on the memory layout, never write code that relies on writing through the result unless you have checked it with np.shares_memory or only use arrays you created contiguously.

Transposing and rearranging axes

The transpose swaps rows and columns: m[i, j] becomes m.T[j, i]. For a 2D array, .T is all you need. It is a view, so it costs nothing, because NumPy only swaps the strides, not the data.

For arrays with three or more axes you decide where each axis goes:

  • a.transpose(1, 0, 2) gives the new order of the axes.
  • np.swapaxes(a, 0, 2) exchanges exactly two axes.
  • np.moveaxis(a, source, destination) moves one axis and keeps the others in order. It is usually the clearest choice.
  • On an array with more than two axes, plain .T reverses all the axes.
Python Transposing and moving axes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line is a very common job: many image libraries store pictures as (height, width, channels), while machine-learning frameworks often want (channels, height, width). np.moveaxis(img, -1, 0) does it without any index arithmetic. You will build images in Arrays as Images and Plots.

Adding and removing axes of length 1

Axes of length 1 are the glue of broadcasting. Two functions create and remove them:

  • np.expand_dims(a, axis) inserts a new axis of length 1. The shortcut a[:, np.newaxis] (or a[:, None]) does the same.
  • np.squeeze(a) removes all axes of length 1. With axis=... it removes only that axis, and raises an error if the axis is not of length 1.
Python expand_dims and squeeze

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A frequent bug is a vector of shape (3,) that you assumed was a column of shape (3, 1). Adding a (3,) and a (3, 1) array gives a (3, 3) table instead of three sums. When results come out with the wrong shape, print .shape first. Aggregations also accept keepdims=True, as the last lines show, which keeps the reduced axis with length 1 so the result can immediately be broadcast back against the original.

Memory order: C versus Fortran

The flat block of numbers can be read in two orders:

  • C order (order="C", the default): the last index varies fastest. Rows are contiguous.
  • Fortran order (order="F"): the first index varies fastest. Columns are contiguous.

Functions such as reshape, ravel and flatten accept order, and it decides in what order elements are read from the old shape and written into the new one. A third value, "K", for ravel, means "read the elements in the order they are in memory".

A first look at strides

How does a view like .T work without moving data? Every array carries strides: for each axis, the number of bytes to jump to reach the next element along that axis. Reshaping or transposing just computes new strides.

Python Order and strides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With 8-byte integers, a has strides (24, 8): moving to the next row jumps over three 8-byte numbers, moving to the next column jumps over one. The transpose has strides (8, 24): same data, the roles swapped. That is why a transpose is free, and also why it cannot be flattened as a view in C order.

The slice b[:, ::2] takes every second column, so the column stride doubles to 16 bytes and the result is no longer contiguous. Non-contiguous arrays are valid and fast to create, but some operations, such as reshape into a very different shape, need to copy them first. The whole story of contiguity, caches and as_strided is in Memory Layout and Strides.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does np.arange(12).reshape(3, -1) produce?

    NumPy replaces -1 with the value that makes the total size match: 12 / 3 = 4 columns.
  2. 2. You call b = a.reshape(2, 6) on a contiguous array and then set b[0, 0] = 99. What happens to a?

    For a contiguous array, reshape returns a view. Writes through the view change the original. Use .copy() when you want independence.
  3. 3. What is the difference between ravel() and flatten()?

    Both return a 1D array, but flatten always allocates a new one, while ravel avoids copying whenever the memory layout allows.
  4. 4. An image has shape (480, 640, 3). Which call gives shape (3, 480, 640)?

    moveaxis moves the last axis to the front and keeps the others in order. reshape would scramble the pixels, and .T would reverse all axes to (3, 640, 480).
  5. 5. Why is m.T essentially free for a large array?

    A transpose reuses the same memory with the strides swapped. Only operations that need the data in a specific order may copy afterwards.

Summary

  • reshape changes the shape, not the data. The element count must match, and one dimension may be -1.
  • reshape and ravel return views when the memory layout allows it; flatten and .copy() always copy.
  • .T reverses the axes. For 3D or higher use transpose, swapaxes or the clearer moveaxis.
  • expand_dims (or None / np.newaxis) adds a length-1 axis, squeeze removes it, and keepdims=True keeps it after a reduction.
  • Arrays are read in C order (rows first) by default; order="F" uses column-major order. Strides are the byte steps per axis that make views possible.

Next, put several arrays together or cut one into pieces in Joining and Splitting.