Reputation: 376
Is there a numpy function that splits an array into equal chunks of size m (excluding any remainder which would have a size less than m). I have looked at the function np.array_split but that doesn't let you split by specifying the sizes of the chunks.
An example of what I'm looking for is below:
X = np.arange(10)
split (X, size = 3)
-> [ [0,1,2],[3,4,5],[6,7,8], [9] ]
split (X, size = 4)
-> [ [0,1,2,3],[4,5,6,7],[8,9]]
split (X, size = 5)
-> [ [0,1,2,3,4],[5,6,7,8,9]]
Upvotes: 11
Views: 9529
Reputation: 7350
def build_chunks(arr, chunk_size, axis=1):
return np.split(arr,
range(chunk_size, arr.shape[axis], chunk_size),
axis=axis)
Upvotes: 1
Reputation: 4462
lst = np.arange(10)
n = 3
[lst[i:i + n] for i in range(0, len(lst), n)]
Upvotes: 0
Reputation: 221514
Here's one way with np.split
+ np.arange/range
-
def split_given_size(a, size):
return np.split(a, np.arange(size,len(a),size))
Sample runs -
In [140]: X
Out[140]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [141]: split_given_size(X,3)
Out[141]: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([9])]
In [143]: split_given_size(X,4)
Out[143]: [array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([8, 9])]
In [144]: split_given_size(X,5)
Out[144]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])]
Upvotes: 19