Skip to content
Advertisement

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?

Advertisement

Answer

def split_padded(a,n):
    padding = (-len(a))%n
    return np.split(np.concatenate((a,np.zeros(padding))),n)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement