Numpy Split Array into Chunks of Equal Size with Remainder

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]]

3 Answers

Here's one way with np.split + -

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])]
1
  def build_chunks(arr, chunk_size, axis=1):
     return np.split(arr, 
                     range(chunk_size, arr.shape[axis], chunk_size), axis=axis) 
lst = np.arange(10)
n = 3
[lst[i:i + n] for i in range(0, len(lst), n)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest