Introduction to NumPy
Joining, reshaping and splitting
Split an array at given indices.
Concatenation joins arrays with np.concatenate((a, b), axis=...):
- axis=0 (the default) joins one below the other (adds rows); the arrays must have the same number of columns.
- axis=1 joins side by side (adds columns); they must have the same number of rows.
- If the other dimension does not match, NumPy raises a ValueError. For example, a 2 × 2 and a 2 × 3 array can be joined along axis=1 into a 2 × 5 array, but not along axis=0.
Reshaping with reshape(rows, columns) changes the shape but never the number of elements. np.arange(10, 22) has 12 elements, so .reshape(3, 4) or .reshape(2, 6) work, but .reshape(5, 3) raises a ValueError.
Splitting with np.split():
- np.split(a, [1, 3]) splits before indices 1 and 3, giving 3 parts: a[:1], a[1:3], a[3:].
- np.split(a, 2) divides a into 2 equal parts; if equal parts are impossible, it raises an error.
- For 2-D arrays, the default splits by rows (axis=0); axis=1 splits by columns: np.split(array4, [1, 2], axis=1) gives column 0, column 1 and the remaining columns.
- N split points always give N + 1 pieces.
Example (new): a = np.arange(1, 11) has 10 elements. a.reshape(2, 5) gives 2 rows of 5; np.split(a, [3, 6, 8]) gives four parts, [1 2 3], [4 5 6], [7 8] and [9 10]; but np.split(a, 3) fails, since 10 cannot be divided into 3 equal parts.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.