2

I know that np.array_split allows us to split a NumPy array, but the number of elements in the split arrays only depends on the number of split chunks. The following example shows what I get and what I wish to get (the size of my_array is 35):

my_array = [1 1 1 1 1 0 0 0 1 1 0 1 1 1 0 1 0 1 0 0 0 0 1 0 0 1 0 1 1 0 0 1 1 1 1]
np.array_split(my_array, 5) outputs:

[array([1, 1, 1, 1, 1, 0, 0]),
 array([0, 1, 1, 0, 1, 1, 1]),
 array([0, 1, 0, 1, 0, 0, 0]),
 array([0, 1, 0, 0, 1, 0, 1]),
 array([1, 0, 0, 1, 1, 1, 1])]

AND 

np.array_split(my_array, 4) outputs:
[array([1, 1, 1, 1, 1, 0, 0, 0, 1]),
 array([1, 0, 1, 1, 1, 0, 1, 0, 1]),
 array([0, 0, 0, 0, 1, 0, 0, 1, 0]),
 array([1, 1, 0, 0, 1, 1, 1, 1])]

However, what I need is split arrays with 8 elements like this: 
[array([1, 1, 1, 1, 1, 0, 0, 0]),
 array([1, 1, 0, 1, 1, 1, 0, 1]),
 array([0, 1, 0, 0, 0, 0, 1, 0]),
 array([0, 1, 0, 1, 1, 0, 0, 1]),
 array([1, 1, 1])

I know that np.array_split(my_array, [8, 16, 24, 32]) can give me the answer for this specific question, but what I wish to do is that, for any size of an array, I could split it into arrays with a specific number of elements except for the last one if the array is not divisible.

0

3 Answers 3

3

You are close:

my_array = np.arange(35)
N = 8
>>> np.array_split(my_array, range(N, len(my_array), N))
[array([0, 1, 2, 3, 4, 5, 6, 7]),
 array([ 8,  9, 10, 11, 12, 13, 14, 15]),
 array([16, 17, 18, 19, 20, 21, 22, 23]),
 array([24, 25, 26, 27, 28, 29, 30, 31]),
 array([32, 33, 34])]
Sign up to request clarification or add additional context in comments.

Comments

0
np.array_split(my_array, (my_array.shape[0] + 7) // 8 )

You can of course generalize that to

np.array_split(my_array, (my_array.shape[0] + N - 1) // N )

Comments

0

A possible solution would be to use the chunked function from more-itertools

list(chunked(my_array, N))

Returns a list of lists all with size N except, possibly, the last.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.