Q&A library Python

What does -1 mean in NumPy reshape?

Python Intermediate arraysnumpyreshape

Short answer

Passing -1 as a dimension tells NumPy to work out that size itself from the total number of elements. It is a convenience so you do not have to compute the length by hand, and only one dimension may be -1.

The short version

In reshape, -1 is a placeholder meaning "you figure out this dimension". NumPy computes it from the total number of elements and the other dimensions you specified. It saves you calculating a length by hand and keeps code working when the array size changes. Only one dimension may be -1, because NumPy can solve for a single unknown.

A worked example

import numpy as np

a = np.arange(6)          # [0 1 2 3 4 5]

print(a.reshape(2, -1))   # 2 rows, columns inferred as 3
print(a.reshape(-1, 3))   # 3 columns, rows inferred as 2

Both produce a 2 by 3 array. In the first, you fixed 2 rows and let NumPy work out 3 columns; in the second, you fixed 3 columns and it worked out 2 rows.

Why it is useful

Without -1 you must compute the other dimension yourself, which is fiddly and breaks if the array size changes.

a.reshape(2, len(a) // 2)   # the manual equivalent, more brittle

Using -1 lets the same reshape adapt to arrays of different lengths, as long as the total divides evenly, so it is both shorter and more robust.

The common use: flatten to a column or row

Two very frequent shapes are a single column and a single row, which come up constantly when feeding data into libraries that expect a 2D shape.

a.reshape(-1, 1)   # a column: shape (6, 1)
a.reshape(1, -1)   # a row: shape (1, 6)

reshape(-1) on its own flattens any array back to one dimension, which is handy after multidimensional operations.

The rule: only one unknown

You cannot use -1 twice, because NumPy would have two unknowns and no way to solve them.

a.reshape(-1, -1)   # ValueError: can only specify one unknown dimension

Fix at least all but one dimension, and let -1 cover the last.

The size-must-divide requirement

The total number of elements must fit the shape exactly, or reshape raises. Six elements cannot become a 4 by something array, because 6 is not divisible by 4.

a.reshape(4, -1)   # ValueError: cannot reshape array of size 6 into shape (4, newaxis)

If you hit this error, check that your intended dimension divides the element count. It usually means the data is not the size you assumed, which is itself worth knowing.

reshape returns a view

Where possible, reshape returns a view onto the same data rather than a copy, so it is cheap. That also means editing the reshaped array can change the original, the same view behaviour that applies to slicing, so copy first if you need independence.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project