Sub topic 12
Concatenating and Stacking
This chapter assumes you know the ndarray basics from earlier chapters: shape, ndim, dtype, and axes. Joining arrays looks simple, but most errors come from confusing two operations. One extends an existing axis. The other creates a new axis.
Two ways to join arrays
NumPy has two core joining operations:
np.concatenatejoins arrays along an axis that already exists. The number of dimensions stays the same.np.stackjoins arrays along a new axis. The number of dimensions goes up by one.
Everything else (vstack, hstack, dstack, column_stack) is a convenience wrapper around these two ideas.
Both functions take a sequence of arrays, such as a list or tuple, as the first argument. Passing the arrays as separate arguments, as in np.concatenate(a, b), fails because b is read as the axis argument.
np.concatenate
Arrays must have the same number of dimensions. Their shapes must match on every axis except the one you join along.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
b = np.array([[7, 8, 9]]) # shape (1, 3)
c = np.array([[10], [20]]) # shape (2, 1)
rows = np.concatenate([a, b], axis=0)
print(rows.shape) # (3, 3)
print(rows)
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
cols = np.concatenate([a, c], axis=1)
print(cols.shape) # (2, 4)
print(cols)
# [[ 1 2 3 10]
# [ 4 5 6 20]]The joined axis grows to the sum of the input sizes: 2 + 1 rows in the first call, 3 + 1 columns in the second. All other axes keep their size.
If the other axes do not match, NumPy raises a ValueError. Joining a and c with axis=0 fails because the column counts are 3 and 1. The message names the offending dimension and the two sizes.
With axis=None, every input is flattened before joining:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9]])
print(np.concatenate([a, b], axis=None)) # [1 2 3 4 5 6 7 8 9]This is also the only way to join arrays whose dimension counts differ, because flattening makes them all 1-D.
np.stack
np.stack requires every input to have exactly the same shape. It inserts a new axis at the position you give in axis.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
print(np.concatenate([x, y])) # [1 2 3 4 5 6], shape (6,)
s0 = np.stack([x, y]) # axis=0 is the default
print(s0.shape) # (2, 3)
s1 = np.stack([x, y], axis=1)
print(s1.shape) # (3, 2)
print(s1)
# [[1 4]
# [2 5]
# [3 6]]The same two 1-D arrays give a 1-D result with concatenate and a 2-D result with stack. Use stack when each input is one item in a collection, such as one sample, one image, or one time step. Use concatenate when each input is a chunk of the same axis.
stack is equivalent to adding a length-1 axis to each input with np.expand_dims (or np.newaxis) and then calling concatenate along that axis.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
manual = np.concatenate([x[np.newaxis, :], y[np.newaxis, :]], axis=0)
print(np.array_equal(manual, np.stack([x, y]))) # TrueNegative axes work. For two arrays of shape (2, 3), np.stack(..., axis=-1) gives shape (2, 3, 2), which puts the new axis last.
Convenience wrappers
The wrappers pick the axis for you, and they add dimensions to low-dimensional inputs. That second behavior is the source of most surprises.
| Function | Behavior | Two `(2, 3)` inputs give | Two `(3,)` inputs give |
|---|---|---|---|
| `np.concatenate(axis=0)` | Extends axis 0 | `(4, 3)` | `(6,)` |
| `np.stack(axis=0)` | New leading axis | `(2, 2, 3)` | `(2, 3)` |
| `np.vstack` | Extends axis 0 after making inputs at least 2-D | `(4, 3)` | `(2, 3)` |
| `np.hstack` | Extends axis 1, but axis 0 for 1-D inputs | `(2, 6)` | `(6,)` |
| `np.column_stack` | Treats 1-D inputs as columns, then joins on axis 1 | `(2, 6)` | `(3, 2)` |
| `np.dstack` | Extends axis 2 after making inputs at least 3-D | `(2, 3, 2)` | `(1, 3, 2)` |
Two rows deserve a closer look:
vstackturns a(3,)array into(1, 3)first. That is why stacking two 1-D arrays gives a 2-D result.hstackdoes not add dimensions to 1-D inputs. It simply concatenates them. Two(3,)arrays become(6,), not(3, 2). To place 1-D arrays side by side as columns, usecolumn_stackornp.stack(..., axis=1).
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)
print(np.dstack([x, y]).shape) # (1, 3, 2)In new code, prefer concatenate and stack with an explicit axis. The axis is then visible in the code, and you do not need to remember how each wrapper treats 1-D input.
Dtypes and copies
When inputs have different dtypes, the result uses the promoted dtype, the smallest type that can hold all the inputs.
import numpy as np
ints = np.array([1, 2])
floats = np.array([0.5])
joined = np.concatenate([ints, floats])
print(joined) # [1. 2. 0.5]
print(joined.dtype) # float64The integers are converted to floats silently. Check dtype after a join if you expect integers to stay integers.
Joining always allocates new memory and copies the data. The result is never a view of the inputs, so changing it does not change the originals.
import numpy as np
a = np.arange(3)
b = np.arange(3)
r = np.concatenate([a, b])
print(np.shares_memory(a, r)) # False
r[0] = 99
print(a) # [0 1 2]The cost is proportional to the total size of the result.
Pitfall: joining inside a loop
Because every join copies all the data, growing an array one piece at a time is quadratic. The first iteration copies one chunk, the second copies two, the third copies three, and so on. np.append is a thin wrapper over concatenate, so it has the same cost. Without an axis argument it also flattens its inputs, which surprises many people.
Collect pieces in a Python list and join once at the end:
import numpy as np
pieces = []
for i in range(4):
pieces.append(np.arange(3) * i)
table = np.stack(pieces) # one copy, shape (4, 3)
print(table)
# [[0 0 0]
# [0 1 2]
# [0 2 4]
# [0 3 6]]If you know the final size in advance, you can instead allocate with np.empty((4, 3)) and fill rows by assignment. That avoids the temporary list of arrays.
Splitting: the inverse
np.split(arr, n, axis=...) cuts an array into n equal pieces and returns a list of views. It raises an error if the axis length is not divisible by n. np.array_split allows uneven pieces. Splitting and then concatenating on the same axis restores the original array.
import numpy as np
m = np.arange(12).reshape(4, 3)
top, bottom = np.split(m, 2, axis=0)
print(top.shape, bottom.shape) # (2, 3) (2, 3)
print(np.array_equal(np.concatenate([top, bottom]), m)) # TrueCommon errors
- Dimension mismatch.
concatenateneeds equalndim. Add a length-1 axis withx[np.newaxis, :]orx[:, np.newaxis], or usestack. - Shape mismatch off the join axis. Print the shapes before joining. The error message points at the first mismatching dimension.
- Wrong wrapper for 1-D input.
hstackof 1-D arrays does not produce columns. - Unexpected dtype. Mixing integers and floats gives floats. Mixing in strings can give a string dtype.
- Expecting a view. Mutating the result never changes the inputs.
Exercise
You have two 1-D arrays, u and v, each of shape (4,). You want a result of shape (4, 2) whose first column is u and whose second column is v. Give two different expressions that do this, and explain why np.hstack([u, v]) does not.
Show answer
Use np.stack([u, v], axis=1) or np.column_stack([u, v]). Both give shape (4, 2). np.hstack on 1-D inputs concatenates along axis 0 without adding a dimension, so it returns shape (8,).
Exercise
A loop runs 10,000 times. Each pass computes a 1-D array of 100 values and does result = np.concatenate([result, new]). Why is this slow, and how should you restructure it?
Show answer
Each call allocates a new array and copies everything accumulated so far, so the total copying grows quadratically with the number of iterations. Append each new to a Python list inside the loop and call np.concatenate(list_of_arrays) once after the loop. Alternatively, preallocate np.empty(10_000 * 100) and fill slices.