简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM