reshape()
Rearrange the same data into a new shape — the total-elements rule, the -1 placeholder, splitting a season into halves, and C vs F order.
Watch the lesson
1 video on CodeWithMunnaX
Virat's 12 innings arrive as one long list. But you might want them as 3 rows of 4 (one row per month), or 2 rows of 6 (first half vs second half of the season). The numbers don't change — only how they are arranged. That is exactly what reshape does.
Definition
reshapereturns the same data arranged into a new shape (a new number of rows, columns or dimensions). It never adds, removes or changes values — so the total number of elements must stay the same. Whenever possible the result is a view that shares memory with the original.
- Same data — the values are read in order (row by row by default) and poured into the new shape.
- Total must match — a 12-element array can become
(3, 4),(2, 6),(12, 1)or(2, 2, 3)because 3×4 = 2×6 = 12×1 = 2×2×3 = 12. It can never become(5, 3)(15 ≠ 12). - View — the reshaped array usually points at the same memory, so changing one changes the other (see Copy vs View).
text
runs (12,): [72 45 88 31 64 0 103 52 19 77 41 93]
reshape(3, 4): reshape(2, 6):
[[ 72 45 88 31] [[ 72 45 88 31 64 0]
[ 64 0 103 52] [103 52 19 77 41 93]]
[ 19 77 41 93]]Syntax
python
a.reshape(shape, order="C") # method form: a.reshape(3, 4) or a.reshape((3, 4))
np.reshape(a, shape, order="C") # function form
a.reshape(-1) # -1 = "work this dimension out for me"| Parameter | Meaning | Default |
|---|---|---|
a | the array to reshape | — required |
shape | the new shape: an int or a tuple of ints; one entry may be -1 | — required |
order | the order elements are read and placed: "C" = row by row, "F" = column by column | "C" |
copy | (NumPy 2.1+) True = always copy, False = error if a view is impossible, None = view when possible | None |
Note: the method accepts the shape as separate numbers (
a.reshape(3, 4)) or as a tuple (a.reshape((3, 4))). The function form needs a tuple:np.reshape(a, (3, 4)).
The rules of reshape
- Product of the new shape =
a.size. Otherwise:ValueError: cannot reshape array of size 12 into shape (5,3). - At most one
-1. NumPy computes it asa.size ÷ (product of the other numbers); two unknowns are ambiguous →ValueError: can only specify one unknown dimension. - Order is preserved. Reading the new array row by row gives the same sequence as the original (with
order="C"). - Reshape does not modify
a. It returns a new array object;a.shapeis unchanged unless you reassign:a = a.reshape(3, 4).
Example — valid and invalid shapes
python
import numpy as np
runs = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77, 41, 93])
print("size:", runs.size, " shape:", runs.shape)
print(runs.reshape(3, 4))
print(runs.reshape(2, 2, 3).shape)
print(runs.reshape(12, 1).shape)
try:
runs.reshape(5, 3)
except ValueError as e:
print("ValueError:", e)
print("runs is unchanged:", runs.shape)text
size: 12 shape: (12,)
[[ 72 45 88 31]
[ 64 0 103 52]
[ 19 77 41 93]]
(2, 2, 3)
(12, 1)
ValueError: cannot reshape array of size 12 into shape (5,3)
runs is unchanged: (12,)How it works: (3, 4), (2, 2, 3) and (12, 1) all hold exactly 12 elements, so they succeed. (5, 3) needs 15, so NumPy refuses. The original runs keeps its shape (12,).
Example — the -1 placeholder
python
import numpy as np
runs = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77, 41, 93])
print(runs.reshape(2, -1).shape) # 12 / 2 -> 6
print(runs.reshape(-1, 3).shape) # 12 / 3 -> 4
print(runs.reshape(2, 3, -1).shape) # 12 / 6 -> 2
print(runs.reshape(-1, 1).shape) # a column vector
print(runs.reshape(3, 4).reshape(-1)) # back to 1D
try:
runs.reshape(-1, -1)
except ValueError as e:
print("ValueError:", e)text
(2, 6)
(4, 3)
(2, 3, 2)
(12, 1)
[ 72 45 88 31 64 0 103 52 19 77 41 93]
ValueError: can only specify one unknown dimension| Code | Total elements | Calculated shape |
|---|---|---|
reshape(2, -1) | 12 | (2, 6) |
reshape(-1, 3) | 12 | (4, 3) |
reshape(2, 3, -1) | 12 | (2, 3, 2) |
reshape(-1, 1) | 12 | (12, 1) — a column |
reshape(-1) | 12 | (12,) — flat |
reshape(-1, -1) | — | ❌ Error |
-1 is extremely common in real code: reshape(-1, 1) turns any 1D array into a column (needed for per-row broadcasting and for scikit-learn), and reshape(-1) flattens anything.
Example — split a season into two halves
This is the course notebook's practical use: reshape (players, matches) into (players, half, matches_per_half) to compare form.
python
import numpy as np
players = ["Virat", "Rohit"]
scores = np.array([
[72, 45, 88, 31, 64, 0, 103, 52, 19, 77, 41, 93],
[56, 0, 74, 88, 32, 45, 61, 17, 90, 38, 72, 5],
])
halves = scores.reshape(2, 2, 6) # axis 1: 0 = first half, 1 = second half
print("shape:", halves.shape)
avg = halves.mean(axis=2) # average inside each half
for name, (first, second) in zip(players, avg):
trend = "Improving" if second > first else "Declining"
print(f"{name:<6} 1st half {first:5.1f} 2nd half {second:5.1f} {trend}")text
shape: (2, 2, 6)
Virat 1st half 50.0 2nd half 64.2 Improving
Rohit 1st half 49.2 2nd half 47.2 DecliningHow it works: each player's 12 scores are split row by row into 2 groups of 6. mean(axis=2) averages over the 6 matches inside each half, giving a (2, 2) table: players × halves.
Example — order="C" vs order="F"
python
import numpy as np
a = np.arange(1, 7)
print("C order (row by row):")
print(a.reshape(2, 3, order="C"))
print("F order (column by column):")
print(a.reshape(2, 3, order="F"))text
C order (row by row):
[[1 2 3]
[4 5 6]]
F order (column by column):
[[1 3 5]
[2 4 6]]How it works: "C" (named after the C language) fills the first row completely, then the next. "F" (Fortran) fills the first column first. You will almost always use the default "C"; "F" appears when data comes from MATLAB/Fortran or column-major files.
Common mistakes
- ❌
runs.reshape(5, 3)on 12 elements →ValueError: cannot reshape array of size 12 into shape (5,3). ✅ Multiply your shape out first; it must equala.size. - ❌ Calling
runs.reshape(3, 4)and expectingrunsitself to change. ✅ Reassign:runs = runs.reshape(3, 4). - ❌ Using two
-1s. ✅ Only one dimension can be unknown. - ❌ Thinking reshape is the same as transpose. ✅
reshape(4, 3)of a(3, 4)array re-reads the values in order;.Tswaps rows and columns. They give different arrays (see the next topics). - ❌ Assuming the reshaped array is independent. ✅ It is usually a view — modifying it changes the original. Use
.copy()if needed.
Comparison — ways to change shape
| Tool | Changes data order? | Returns | Use when |
|---|---|---|---|
a.reshape(r, c) | no | a new array (view if possible) | you need a new arrangement |
a.shape = (r, c) | no | modifies a in place (error if a copy would be needed) | rare; prefer reshape |
a.resize((r, c)) | no | in place; can grow/shrink (pads with 0) | rare |
np.resize(a, (r, c)) | no | new array; repeats data to fill | rare |
a.T | yes — swaps axes | a view | rows ↔ columns |
Interview tip
Q: What does reshape(-1, 1) do and why is it so common?
A: It turns any array into a column vector of shape (n, 1), letting NumPy compute n. It's used to make a 1D array broadcast per-row against a 2D array, and because libraries like scikit-learn require 2D input of shape (samples, features).
Key points to remember
- reshape rearranges the same values into a new shape; it never adds, removes or changes data.
- The product of the new shape must equal a.size — otherwise ValueError: cannot reshape array of size N into shape ….
- Use -1 for exactly one dimension and NumPy calculates it; reshape(-1) flattens, reshape(-1, 1) makes a column.
- Values are read and placed row by row (order='C'); order='F' fills column by column.
- reshape returns a new array object (usually a view) — the original keeps its shape unless you reassign.
- Reshaping (players, 12) into (players, 2, 6) is a quick way to split a season into halves.
- reshape is not transpose: reshape re-reads in order, .T swaps rows and columns.
Try it yourself
Valid reshapes of 12 innings
Let NumPy compute -1
C order vs F order
Practice: first half vs second half
Revision Flashcards
Tap a card to flip it and see the answer.
