NumPy Array Split
Splitting is the reverse of joining: it breaks one array into several smaller ones. The main function is np.array_split(array, sections), which returns a list of arrays.
import numpy as np
tickets = np.arange(1, 13) # ticket numbers 1..12
parts = np.array_split(tickets, 3) # three equal groups
print(parts)
for i, part in enumerate(parts):
print(f"group {i}: {part}")[array([1, 2, 3, 4]), array([5, 6, 7, 8]), array([ 9, 10, 11, 12])]
group 0: [1 2 3 4]
group 1: [5 6 7 8]
group 2: [ 9 10 11 12]
When the split isn't even
np.array_split handles leftovers gracefully: the first pieces get one extra element each. np.split is stricter and raises an error when the array can't be divided evenly:
import numpy as np
players = np.arange(1, 11) # 10 players
teams = np.array_split(players, 3) # 4 + 3 + 3
print([t.tolist() for t in teams])
try:
np.split(players, 3)
except ValueError as err:
print("ValueError:", err)[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
ValueError: array split does not result in an equal division
| Function | Uneven sizes? |
|---|---|
np.array_split(a, n) |
allowed: sizes differ by at most one |
np.split(a, n) |
ValueError unless len(a) is divisible by n |
Splitting at given positions
Instead of a count, you can pass a list of indices where cuts happen. This works with both functions:
import numpy as np
log = np.array([3, 8, 1, 9, 4, 7, 2, 6])
head, middle, tail = np.split(log, [2, 5]) # cut before index 2 and before index 5
print(head, middle, tail)[3 8] [1 9 4] [7 2 6]
Cutting at [2, 5] produces log[:2], log[2:5] and log[5:]. Unpacking the list into named variables, as above, keeps the code readable.
Splitting 2-D arrays
Use axis to choose the direction. axis=0 cuts between rows, axis=1 cuts between columns:
import numpy as np
grid = np.arange(1, 25).reshape(4, 6)
top, bottom = np.array_split(grid, 2) # axis=0 by default
print(top)
print(bottom)
left, mid, right = np.array_split(grid, 3, axis=1)
print(mid)[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
[[13 14 15 16 17 18]
[19 20 21 22 23 24]]
[[ 3 4]
[ 9 10]
[15 16]
[21 22]]
Shortcut functions
Mirroring hstack and vstack, there are np.hsplit (columns), np.vsplit (rows) and np.dsplit (depth). Like np.split, they require an even division when given a count:
import numpy as np
# A 2x4 table: x values in the first 2 columns, labels in the last 2
data = np.array([[1, 2, 0, 1],
[3, 4, 1, 0]])
features, labels = np.hsplit(data, 2)
print(features)
print(labels)
first_row, second_row = np.vsplit(data, 2)
print(first_row, second_row.shape)[[1 2]
[3 4]]
[[0 1]
[1 0]]
[[1 2 0 1]] (1, 4)
Splitting for training and testing
A very common real use: separate a dataset into a training part and a test part.
import numpy as np
samples = np.arange(100, 110) # 10 record ids (assume already shuffled)
cut = int(len(samples) * 0.8) # 80 % for training
train, test = np.split(samples, [cut])
print("train:", train)
print("test: ", test)train: [100 101 102 103 104 105 106 107]
test: [108 109]
Note: The pieces returned by splitting are views of the original array, so modifying one piece modifies the original data.
Test yourself
What sizes do you get from np.array_split(np.arange(7), 3)?
- 3, 2, 2
- 2, 2, 3
- 3, 3, 1
- An error
What does np.split(np.arange(6), [1, 4]) return?
- [0], [1 2 3], [4 5]
- [0 1], [2 3 4], [5]
- [0], [1 2 3 4], [5]
- Three equal pieces
Which function splits a 2-D array into groups of columns?
- np.vsplit
- np.hsplit
- np.dsplit
- np.rsplit