Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to split an array into n parts. Sometimes these parts are of the same size, sometimes they are of a different size.

I am trying to use:

split = np.split(list, size)

This works fine when size divides equally into the list, but fails otherwise. Is there a way to do this which will 'pad' the final array with the extra 'few' elements?

share|improve this question

2 Answers 2

up vote 1 down vote accepted
def split_padded(a,n):
    padding = (-len(a))%n
    return np.split(np.concatenate((a,np.zeros(padding))),n)
share|improve this answer

Are you looking for np.array_split ? Here is the docstring:

Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally 
divide the axis.

See Also
--------
split : Split array into multiple sub-arrays of equal size.

Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.