NumPy Array Split
Splitting an array breaks one array into several smaller arrays, the opposite operation of joining.
Why Split Arrays?
Splitting is the mirror image of joining: instead of combining pieces into a whole, you break a whole array into smaller pieces. This comes up constantly in real workflows — dividing a dataset into training and validation batches, chunking a large array so it fits in memory, or distributing rows of work across multiple parallel processes.
np.array_split(): Flexible Splitting
np.array_split() takes an array and the number of pieces you want, and divides the array as evenly as possible. Unlike the stricter np.split(), which raises an error if the array cannot be divided evenly, array_split() simply makes some pieces slightly larger than others when the split count doesn't divide evenly — which makes it the safer default choice for most code.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
# Even split into 3 equal parts
result = np.array_split(arr, 3)
print(result)
# [array([1, 2]), array([3, 4]), array([5, 6])]
# Uneven split into 4 parts still works
result2 = np.array_split(arr, 4)
print(result2)
# [array([1, 2]), array([3, 4]), array([5]), array([6])]Splitting 2D Arrays Along an Axis
For 2D arrays, array_split() accepts an axis argument just like concatenate(). axis=0 (the default) splits the array row-wise, producing groups of rows. axis=1 splits column-wise, producing groups of columns. Choosing the right axis depends on whether you are dividing records (rows) or features (columns).
Example
import numpy as np
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Split into 2 groups of columns
col_parts = np.array_split(matrix, 2, axis=1)
print(col_parts)
# [array([[1, 2], [5, 6], [9, 10]]),
# array([[3, 4], [7, 8], [11, 12]])]- np.hsplit(arr, n) — splits horizontally (column-wise); a shortcut for array_split(arr, n, axis=1).
- np.vsplit(arr, n) — splits vertically (row-wise); a shortcut for array_split(arr, n, axis=0).
- np.split(arr, n) — like array_split(), but raises a ValueError if the array cannot be divided into n equal parts.
- Each function returns a Python list of arrays, not a single array — index into the list to access an individual chunk.
Example
import numpy as np
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
# hsplit: split into 2 column groups
print(np.hsplit(matrix, 2))
# [array([[1, 2], [5, 6]]), array([[3, 4], [7, 8]])]
# vsplit: split into 2 row groups
print(np.vsplit(matrix, 2))
# [array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]Exercise: NumPy Array Split
Which function splits an array into sub-arrays of unequal size without raising an error?