reshape() (NumPy)

a.reshape() returns a new view of an array with a different shape but the same data and the same total number of elements. It rearranges how the existing values are organized into rows, columns, or higher dimensions.

NumPy

reshape lets you turn a flat array of 6 elements into a 2-by-3 or 3-by-2 grid without copying the underlying buffer — the data stays put and only the indexing changes. The new shape must contain the same number of elements; otherwise NumPy raises an error.

You can pass -1 for one dimension to have NumPy infer it: arange(12).reshape(3, -1) figures out that the second axis must be 4. This is the idiomatic way to reshape when you only know some of the dimensions.

Because reshape usually returns a view rather than a copy, writing to the reshaped array can change the original. When you specifically want to flatten back to 1-D, ravel (a view) or flatten (a copy) do the job.

Syntax

a.reshape(shape)  |  np.reshape(a, shape)

Examples

Python

import numpy as np
print(np.arange(6).reshape(2, 3))

Output:

[[0 1 2]
 [3 4 5]]

Learn it in a lesson

See also

Back to the Dictionary