import numpy as np
ar = np.array([1, 2, 3, 4, 5, 6])
result = ar.reshape(2, 3)
print(result) # [[1 2 3] [4 5 6]]
numpy.reshape(a, newshape, order='C') The reshape() function is fundamental for transforming 1D flat sequences into 2D matrices, 3D image tensors, or vice-versa. Total element count must remain identical (e.g., 12 elements can be shaped as (3, 4), (2, 6), or (2, 2, 3)). For structural cloning without initialization, see empty_like(). For array slicing and indexing, review Indexing & Slicing.
| Parameter | Description |
|---|---|
a | Array to be reshaped |
newshape | Int or tuple of ints defining the new shape. One dimension can be -1 for automatic inference |
order | Memory layout order: 'C' (row-major C-style), 'F' (column-major Fortran-style), or 'A' (aligned) |
numpy.reshape(a, newshape, order='C')
# Or as an ndarray method:
a.reshape(newshape, order='C')
The table below highlights how legacy NumPy reshape snippets compare against the modernized, structured implementation:
| Aspect | Legacy Implementation | Modernized Implementation |
|---|---|---|
| Structure & Markup | Basic echo output with unformatted pre tags and missing metadata. | Structured HTML5 layout, Schema TechArticle markup, and responsive tables. |
| Code Presentation | Requires scrolling past introductory text to find code examples. | Core code snippet placed right at the top for instant visitor access. |
| Verification | Unchecked print statements with manual result inspection comments. | Automated unit test assertions (assert) verifying shape and dimensions. |
| Ecosystem Integration | Isolated code blocks with sparse navigation links. | Comprehensive cross-linking, quick-jump navigation, and runnable Colab notebooks. |
Transform a flat 1D array into a multi-dimensional matrix:
import numpy as np
ar = np.arange(12)
ar_reshaped = ar.reshape(3, 4)
print("Reshaped 3x4 matrix:
", ar_reshaped)
assert ar_reshaped.shape == (3, 4)
Expected output
Reshaped 3x4 matrix:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
You can let NumPy automatically calculate one dimension by passing -1:
ar = np.arange(12)
# Automatically infer column count for 4 rows
auto_mat = ar.reshape(4, -1)
print("Inferred 4x3 matrix:
", auto_mat)
assert auto_mat.shape == (4, 3)
Expected output
Inferred 4x3 matrix:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
The order parameter controls how elements are read from and written to memory. 'C' uses row-major order (C-style), while 'F' uses column-major order (Fortran-style):
ar = np.arange(6)
c_order = ar.reshape(2, 3, order='C')
f_order = ar.reshape(2, 3, order='F')
print("C order (row-major):
", c_order)
print("F order (column-major):
", f_order)
assert c_order[0, 1] == 1
assert f_order[0, 1] == 2
Expected output
C order (row-major):
[[0 1 2]
[3 4 5]]
F order (column-major):
[[0 2 4]
[1 3 5]]
To collapse multi-dimensional arrays back into 1D sequences, use ravel() (returns a view when possible) or flatten() (always returns a copy):
mat = np.array([[1, 2], [3, 4]])
rav = mat.ravel()
flat = mat.flatten()
print("Ravel (view):", rav)
print("Flatten (copy):", flat)
assert rav.ndim == 1
assert flat.ndim == 1
Expected output
Ravel (view): [1 2 3 4]
Flatten (copy): [1 2 3 4]
(3, 5) raises ValueError: cannot reshape array of size 12 into shape (3,5) because 3 × 5 = 15 ≠ 12.-1. Specifying multiple unknown dimensions (e.g., arr.reshape(-1, -1)) raises a ValueError.Test 1D/2D reshaping, automatic dimension inference, C vs Fortran order, flattening, and run verification test suites in our interactive Google Colab companion notebook:
Launch the notebook directly in Google Colab to run live code cells or inspect the source repository on GitHub:
View on GitHubreshape() tries to return a memory-efficient view whenever possible. However, if the source array is non-contiguous in memory, it may return a copied array. Use flags.owndata or check base to verify whether data is shared.
Python will raise a ValueError because NumPy can only automatically infer one unknown dimension at a time. The remaining dimensions must be explicitly specified so the total element count can be calculated.
reshape() returns a new view or copy with a different shape without altering the original array data or dimensions, whereas resize() modifies the array shape in-place and can optionally zero-fill or truncate data.
array(), arange(), and linspace() for initializing multi-dimensional datasets.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.