Module 1 · Lesson 5
Combining & Splitting Arrays
np.concatenate([a, b], axis=...)joins arrays along an existing axis (shapes must match on every other axis).np.vstack/np.hstackare convenience wrappers for concatenating along axis 0 / axis 1.np.stack([a, b], axis=...)joins arrays along a new axis instead — use this when you want to go from several(n,)arrays to one(2, n)or(n, 2)array.np.split(arr, n, axis=...)divides an array intonequal pieces along an axis.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate([a, b])) # (6,)
print(np.stack([a, b])) # (2, 3) — new axis 0
print(np.stack([a, b], axis=1)) # (3, 2) — new axis 1
m = np.arange(8).reshape(2, 4)
left, right = np.split(m, 2, axis=1)
print(left)
print(right)
Output:
[1 2 3 4 5 6]
[[1 2 3]
[4 5 6]]
[[1 4]
[2 5]
[3 6]]
[[0 1]
[4 5]]
[[2 3]
[6 7]]
5.1
Interleave two signals
Write interleave(a, b) that takes two 1-D arrays of the same length n
and returns a single 1-D array of length 2n where values alternate:
[a[0], b[0], a[1], b[1], ...]. Do this using np.stack and reshape —
no Python loop.
💡 Hint
np.stack([a, b], axis=1) gives you an (n, 2) array of pairs — flatten that.
✅ Solution
def interleave(a, b):
return np.stack([a, b], axis=1).ravel()
🎯 Key Takeaways
- NumPy arrays beat Python lists for numeric work because they’re contiguous, fixed-type, and support vectorized operations in compiled code.
- Pick the right creation function for the job:
np.arrayfrom existing data,np.zeros/ones/full/eyefor placeholders,np.arange/np.linspacefor ranges. .shape,.ndim,.size,.dtypetell you everything about an array’s layout;.astypeconverts between dtypes (and can silently lose data)..reshape,.ravel,.flatten,.T, andnp.newaxisrearrange data without changing its values.np.concatenate/vstack/hstackjoin along an existing axis;np.stackcreates a new one.
Next up: Module 2 — Indexing, Slicing & Views, where you’ll learn how to select exactly the data you want — and which selections give you a view vs. a copy.