Combining arrays
np.concatenate
Concatenate along an axis.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate([a, b]))For 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.concatenate([a, b], axis=0)) # stack rows
print(np.concatenate([a, b], axis=1)) # stack colsnp.vstack and np.hstack
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack([a, b]))
print(np.hstack([a, b]))np.stack (adds a new axis)
Unlike concatenate, stack creates a brand-new axis instead of joining along an existing one.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.stack([a, b], axis=0).shape) # (2, 3)
print(np.stack([a, b], axis=1).shape) # (3, 2)Splitting arrays
np.split
import numpy as np
arr = np.arange(10)
a, b = np.split(arr, [6])
print(a)
print(b)np.hsplit and np.vsplit
import numpy as np
mat = np.arange(16).reshape(4, 4)
left, right = np.hsplit(mat, 2)
print(left)
print(right)
top, bottom = np.vsplit(mat, 2)
print(top)
print(bottom)flowchart LR A["Two arrays,
same shape"] --> B["np.vstack
join as rows"] A --> C["np.hstack
join as columns"] A --> D["np.stack
join on a NEW axis"] E["One matrix"] --> F["np.split / hsplit / vsplit
-> pieces back apart"]
Choosing the right joining function
Real data rarely arrives in one array. You might load one file per month, compute features in separate steps, or need to add a new column to an existing table. NumPy gives you several joining functions, and they differ mainly in whether they join along an existing axis or create a new one.
np.concatenateis the general tool. You pass a list of arrays and anaxis. The arrays must match in every dimension except the one you join along.np.vstackis shorthand for joining rows (axis 0), andnp.hstackfor joining columns (axis 1).np.stackcreates a brand-new axis, so the inputs must all have identical shapes.np.column_stackturns 1D arrays into the columns of a 2D array.
The most common beginner surprise is with 1D arrays. np.hstack([a, b]) on two length-3 arrays gives one length-6 array, while np.vstack([a, b]) gives a 2 by 3 matrix. A 1D array has only one axis, so "horizontal" just means "end to end".
A worked example: adding a row and a column
import numpy as np
scores = np.array([[1, 2], [3, 4]])
new_row = np.array([[5, 6]])
table = np.vstack([scores, new_row])
print(table)
# [[1 2]
# [3 4]
# [5 6]]
ids = np.array([[10], [20], [30]])
table = np.hstack([ids, table])
print(table)
# [[10 1 2]
# [20 3 4]
# [30 5 6]]The new row must have the same number of columns as the table, and the new column must have the same number of rows. Note that ids is written as a column (shape 3 by 1). A plain 1D array of length 3 would fail with hstack here, because its dimensions would not match. np.column_stack([ids_1d, table]) is a handy alternative that accepts 1D input.
Splitting into equal or unequal parts
np.split(arr, 5) cuts into five equal pieces and raises an error if the length is not divisible by five. When you need "as equal as possible", use np.array_split:
import numpy as np
arr = np.arange(10)
for part in np.array_split(arr, 3):
print(part)
# [0 1 2 3]
# [4 5 6]
# [7 8 9]Passing a list of indices, as in np.split(arr, [6]), means "cut before these positions", which is ideal for a train and test split of ordered data.
Common mistakes
- Shape mismatches. Joining a 2 by 2 array with a 3 by 3 array along axis 0 raises
ValueErrorbecause the column counts differ. - Forgetting the brackets. The functions take a list or tuple of arrays:
np.concatenate([a, b]), notnp.concatenate(a, b). - Confusing
concatenatewithstack. Concatenating two length-3 arrays gives length 6; stacking them gives shape (2, 3). - Expecting a copy to update the original. Joining always makes a new array. Splits, in contrast, return views, so editing a piece can modify the original data.
When to use each
Use vstack when new observations arrive, hstack or column_stack when you add features, stack when you are building a batch of equally shaped items such as images, and the split functions when you divide data into folds, chunks or train and test parts.
Check your understanding
For two 1D arrays a and b of length 3, what do np.hstack([a, b]) and np.vstack([a, b]) produce?
A 1D array has only one axis, so hstack joins end to end into length 6, while vstack stacks them as two rows.
Show answer
A โ A length-6 array and a 2 by 3 matrix โ A 1D array has only one axis, so hstack joins end to end into length 6, while vstack stacks them as two rows.
What is np.stack([a, b], axis=1).shape for two length-3 arrays?
stack creates a brand-new axis. With axis=1 the new axis goes second, giving (3, 2). With axis=0 the shape would be (2, 3).
Show answer
C โ (3, 2) โ stack creates a brand-new axis. With axis=1 the new axis goes second, giving (3, 2). With axis=0 the shape would be (2, 3).
What does np.array_split(np.arange(10), 3) return?
array_split cuts as evenly as possible, giving [0 1 2 3], [4 5 6] and [7 8 9]. np.split would raise an error for 3 equal pieces.
Show answer
B โ Parts of lengths 4, 3 and 3 โ array_split cuts as evenly as possible, giving [0 1 2 3], [4 5 6] and [7 8 9]. np.split would raise an error for 3 equal pieces.
What are the part lengths from a, b = np.split(np.arange(10), [6])?
The list gives positions to cut before, so the first piece holds indices 0 to 5 (6 items) and the second holds the remaining 4.
Show answer
B โ 6 and 4 โ The list gives positions to cut before, so the first piece holds indices 0 to 5 (6 items) and the second holds the remaining 4.
Next
Continue to: NumPy Random Module for generating reproducible random numbers and sampling.
๐งช Try It Yourself
Exercise 1 โ Stack Two Rows
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 โ Split at an Index
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 โ New Axis with stack
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.