Learning Objectives – after this chapter you will be able to:
- Split arrays into parts with
np.array_split()andnp.split(). - Handle uneven splits.
- Split at specific index positions.
- Split 2-D arrays along rows or columns, including
hsplitandvsplit.
Splitting Arrays
Splitting is the reverse of joining: it breaks one array into several smaller arrays. The result is a list of arrays.
| Function | Behaviour |
|---|---|
np.array_split(arr, n) | Splits into n parts; works even if the parts cannot be equal. |
np.split(arr, n) | Splits into n equal parts; raises an error if that is impossible. |
np.split(arr, [i, j]) | Splits at the given index positions. |
np.hsplit() / np.vsplit() / np.dsplit() | Split along columns / rows / depth. |
array_split() and split()
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
parts = np.array_split(arr, 3)
print(len(parts))
for p in parts:
print(p)Output
3 [1 2] [3 4] [5 6]
Uneven splits
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
for p in np.array_split(arr, 3): # uneven: 3 + 2 + 2
print(p)
try:
np.split(arr, 3)
except ValueError as e:
print("ValueError:", e)Output
[1 2 3] [4 5] [6 7] ValueError: array split does not result in an equal division
Splitting at Index Positions
import numpy as np arr = np.arange(10, 20) first, middle, last = np.split(arr, [3, 7]) # cut before index 3 and 7 print(first) print(middle) print(last)
Output
[10 11 12] [13 14 15 16] [17 18 19]
Splitting 2-D Arrays
Use the axis argument: axis=0 splits the rows, axis=1 splits the columns. vsplit and hsplit are shortcuts.
import numpy as np
m = np.arange(1, 13).reshape(4, 3)
top, bottom = np.array_split(m, 2) # axis=0: rows
print(top)
print(bottom)
for col in np.array_split(m, 3, axis=1): # axis=1: columns
print(col.ravel())Output
[[1 2 3] [4 5 6]] [[ 7 8 9] [10 11 12]] [ 1 4 7 10] [ 2 5 8 11] [ 3 6 9 12]
hsplit and vsplit
import numpy as np m = np.arange(1, 13).reshape(3, 4) left, right = np.hsplit(m, 2) # columns print(left) print(right) print(len(np.vsplit(m, 3))) # rows
Output
[[ 1 2] [ 5 6] [ 9 10]] [[ 3 4] [ 7 8] [11 12]] 3
Key Takeaways
- Splitting returns a list of arrays.
array_split()allows uneven parts;split()requires equal parts or explicit index positions.axis=0/vsplitsplit rows;axis=1/hsplitsplit columns.
Video : Array Split
Question / Answer (15 questions)
Answer : Splitting is the reverse of joining: it breaks one array into several smaller arrays. NumPy returns the pieces as a list of arrays.
Answer : np.split(arr, n) requires the array to divide into n equal parts and raises ValueError otherwise. np.array_split(arr, n) also works when equal division is impossible, making the first parts one element larger.
Answer : Into parts of sizes 3, 2 and 2: [1 2 3], [4 5] and [6 7].
Answer : ValueError: array split does not result in an equal division.
Answer : A Python list whose items are NumPy arrays.
Answer : Pass a list of indexes instead of a number: np.split(arr, [3, 7]) gives arr[:3], arr[3:7] and arr[7:].
Answer : Three arrays: [10 11 12], [13 14 15 16] and [17 18 19].
Answer : Use axis=0 (the default), e.g. np.array_split(m, 2), or the shortcut np.vsplit(m, 2).
Answer : Use axis=1, e.g. np.array_split(m, 3, axis=1), or the shortcut np.hsplit(m, 3).
Answer : hsplit splits along columns (axis 1), vsplit along rows (axis 0) and dsplit along the third axis (depth, axis 2). They are the opposites of hstack, vstack and dstack.
Answer : The first two columns: [[1 2] [5 6] [9 10]].
Answer : Index the returned list, e.g. parts = np.array_split(arr, 3); parts[1]. You can also unpack: a, b, c = np.array_split(arr, 3).
Answer : It is used to divide data into training and testing sets, to process large data in batches, and to separate features (columns) from labels.
Answer : Yes, when given a number of sections it requires equal division like np.split(). Use np.array_split(..., axis=1) for uneven column splits.
Answer : Yes. np.vstack(np.vsplit(m, 3)) rebuilds the original array m, because vsplit separates rows that vstack joins back together.
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- NumPy Developers. (n.d.). Array manipulation routines (concatenate, stack, split …). NumPy API Reference. https://numpy.org/doc/stable/reference/routines.array-manipulation.html
- NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
- VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/