Sub topic 8
Reshaping, Concatenating and Stacking
This chapter assumes you can create arrays, read shape and ndim, and index and slice them. You should also know that a basic slice returns a view. Here you will change an array's shape without changing its data, and combine several arrays into one. Both skills are needed before broadcasting, because most broadcasting work starts with getting shapes to line up.
Reshaping keeps the data and changes the shape
An array stores its elements in one flat block of memory. The shape tells NumPy how to read that block as rows, columns and higher dimensions. reshape gives the same elements a new shape. The total number of elements must stay the same.
import numpy as np
a = np.arange(12)
print(a.shape) # (12,)
m = a.reshape(3, 4)
print(m.shape) # (3, 4)
print(m)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
t = a.reshape(2, 2, 3)
print(t.shape) # (2, 2, 3)Elements are read in row-major order (also called C order). The last index changes fastest. So reshape(3, 4) fills the first row with elements 0 to 3, then the second row with 4 to 7, and so on.
If the sizes do not match, NumPy raises a ValueError.
import numpy as np
a = np.arange(12)
try:
a.reshape(5, 3)
except ValueError as err:
print('error:', err)
# error: cannot reshape array of size 12 into shape (5,3)Letting NumPy infer one dimension
You can pass -1 for one dimension. NumPy computes it from the total size and the other dimensions. Only one -1 is allowed.
import numpy as np
a = np.arange(12)
print(a.reshape(3, -1).shape) # (3, 4)
print(a.reshape(-1, 6).shape) # (2, 6)
print(a.reshape(-1).shape) # (12,)Use -1 when one dimension depends on the data size. It also keeps the code correct if the input length changes.
Reshape usually returns a view
When the new shape can be read from the same memory block, reshape returns a view. Writing through the view changes the original.
import numpy as np
a = np.arange(6)
m = a.reshape(2, 3)
m[0, 0] = 100
print(a) # [100 1 2 3 4 5]
print(np.shares_memory(a, m)) # TrueSometimes the layout in memory cannot be reinterpreted with the new shape, for example after a transpose. In that case reshape quietly returns a copy. You cannot rely on either outcome, so do not write code that depends on reshape sharing memory. If you need an independent array, call .copy(). If you need a guarantee of no copy, assign to the shape attribute, which raises an error when a copy would be needed.
Flattening: ravel and flatten
Two methods turn any array into one dimension.
| Method | Returns | Notes |
|---|---|---|
| `ravel()` | A view when possible, otherwise a copy | Cheap in the common case |
| `flatten()` | Always a copy | Safe to modify freely |
import numpy as np
m = np.arange(6).reshape(2, 3)
r = m.ravel()
f = m.flatten()
r[0] = 50
f[1] = 60
print(m)
# [[50 1 2]
# [ 3 4 5]]The write through r changed m. The write through f did not. Choose flatten() when you will edit the result and want the original untouched.
Transposing and swapping axes
.T reverses the order of all axes. For a 2-D array this swaps rows and columns. np.transpose(a, axes) lets you choose the order, and np.swapaxes(a, i, j) swaps two axes.
import numpy as np
m = np.arange(6).reshape(2, 3)
print(m.T.shape) # (3, 2)
t = np.arange(24).reshape(2, 3, 4)
print(t.T.shape) # (4, 3, 2)
print(np.transpose(t, (1, 0, 2)).shape) # (3, 2, 4)
print(np.swapaxes(t, 0, 2).shape) # (4, 3, 2)Transposing returns a view. It changes how NumPy walks through the same memory, not the memory itself. That is why a later reshape of a transposed array may have to copy.
A 1-D array has only one axis, so .T does nothing to it. This is a frequent source of confusion. To turn a 1-D array into a column, add an axis instead, as shown next.
Adding and removing axes
Many shape problems come down to adding a length-1 axis. There are two equivalent ways: np.newaxis (an alias for None) inside an index, and reshape.
import numpy as np
v = np.arange(3) # shape (3,)
col = v[:, np.newaxis] # shape (3, 1)
row = v[np.newaxis, :] # shape (1, 3)
also_col = v.reshape(-1, 1) # shape (3, 1)
print(col.shape, row.shape, also_col.shape)
# (3, 1) (1, 3) (3, 1)np.squeeze does the reverse. It removes axes of length 1.
import numpy as np
c = np.zeros((3, 1, 4))
print(np.squeeze(c).shape) # (3, 4)
print(np.squeeze(c, axis=1).shape) # (3, 4)Without axis, squeeze removes every length-1 axis. That can be surprising if some batch happens to have size 1. Passing axis explicitly is safer in reusable code.
Concatenating arrays
np.concatenate joins arrays along an existing axis. All arrays must have the same shape except along that axis.
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[5, 6]])
down = np.concatenate([a, b], axis=0)
print(down)
# [[1 2]
# [3 4]
# [5 6]]
print(down.shape) # (3, 2)
c = np.array([[7],
[8]])
across = np.concatenate([a, c], axis=1)
print(across)
# [[1 2 7]
# [3 4 8]]When the other dimensions disagree, NumPy refuses.
import numpy as np
a = np.ones((2, 2))
b = np.ones((3, 3))
try:
np.concatenate([a, b], axis=0)
except ValueError as err:
print('error:', err)The message says that all the input array dimensions except for the concatenation axis must match exactly. Read it as a reminder to check every axis other than the one you are joining along.
Concatenation always creates a new array and copies the data. Building a large array by calling concatenate repeatedly inside a loop copies everything each time, so the cost grows quickly. Collect the pieces in a Python list and call concatenate once at the end.
Stacking creates a new axis
np.stack joins arrays along a new axis. All inputs must have exactly the same shape. The difference from concatenate is whether an axis is created.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
s0 = np.stack([x, y], axis=0)
s1 = np.stack([x, y], axis=1)
cat = np.concatenate([x, y])
print(s0)
# [[1 2 3]
# [4 5 6]]
print(s0.shape) # (2, 3)
print(s1)
# [[1 4]
# [2 5]
# [3 6]]
print(s1.shape) # (3, 2)
print(cat) # [1 2 3 4 5 6]Two 1-D arrays of length 3 give a (6,) array with concatenate. They give a 2-D array with stack. With axis=0 each input becomes a row. With axis=1 each input becomes a column.
The vstack, hstack and column_stack helpers
NumPy also offers shortcuts. They are common in older code, so you should recognize them.
| Function | Behavior |
|---|---|
| `np.vstack` | Stacks vertically, like `concatenate` on axis 0 after making 1-D inputs into rows |
| `np.hstack` | Stacks horizontally, like `concatenate` on axis 1 (axis 0 for 1-D inputs) |
| `np.column_stack` | Treats 1-D inputs as columns and joins them side by side |
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
print(np.vstack([x, y]).shape) # (2, 3)
print(np.hstack([x, y]).shape) # (6,)
print(np.column_stack([x, y]).shape) # (3, 2)Note that hstack on 1-D arrays gives a 1-D result, not a 2-D one. The behavior depends on the input dimensions, which is why concatenate and stack with an explicit axis are easier to reason about.
Splitting is the inverse
np.split cuts an array into equal parts along an axis. np.array_split allows unequal parts when the length does not divide evenly. The results are views of the original.
import numpy as np
a = np.arange(10)
for part in np.array_split(a, 3):
print(part)
# [0 1 2 3]
# [4 5 6]
# [7 8 9]Common mistakes
- Treating
reshapeas in-place. It returns a new array object. The original keeps its shape. - Expecting
reshapeto always share memory, or always copy. Either can happen. - Using
.Ton a 1-D array and expecting a column. - Passing arrays to
np.concatenateas separate arguments instead of one sequence. Writenp.concatenate([a, b]), notnp.concatenate(a, b). The second form treatsbas theaxisargument and fails. - Confusing
stackwithconcatenateand ending up with the wrong number of dimensions. - Reshaping to a shape that merges the wrong axes. The code runs without error but mixes data, because reshape follows memory order and not meaning. Check a few values by hand after any reshape of a multi-dimensional array.
Exercise
You have two arrays, p = np.array([1, 2, 3]) and q = np.array([4, 5, 6]). You need a result of shape (3, 2) whose first column is p and whose second column is q. Write two different expressions that produce it, and say what shape np.concatenate([p, q]) gives.
Show answer
Two options are np.stack([p, q], axis=1) and np.column_stack([p, q]). Both give shape (3, 2). A third option is np.vstack([p, q]).T. The call np.concatenate([p, q]) joins along the existing only axis and gives shape (6,), because no new axis is created.
Exercise
An array a has shape (2, 3, 4). What shape results from a.reshape(6, -1), and what does a.reshape(-1) give? Why does a.reshape(5, -1) fail?
Show answer
a.reshape(6, -1) gives (6, 4), because 24 elements divided into 6 rows leaves 4 per row. a.reshape(-1) gives (24,). a.reshape(5, -1) fails because 24 is not divisible by 5, so NumPy cannot infer an integer size for the second dimension and raises a ValueError.