Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python numpy split array into unequal subarrays

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?

like image 386
user1220022 Avatar asked Mar 29 '12 09:03

user1220022


2 Answers

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

http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array_split.html

like image 118
PhML Avatar answered Sep 19 '22 22:09

PhML


def split_padded(a,n):
    padding = (-len(a))%n
    return np.split(np.concatenate((a,np.zeros(padding))),n)
like image 24
YXD Avatar answered Sep 20 '22 22:09

YXD