0

I have a 1D numpy array that I want to divide to several arrays, based on the number of cells (x) in each array.

For example, if this is the array:

[0, 2, 7, 9, 13]

and x=2

I want to get the following arrays as a result:

[0,2]
[7,9]
[13]

I feel that there is a simple way to do it without using loops, but I couldn't find it.

Thank you!

5
  • So, you want a list of arrays? Because a single array as output isn't possible. Commented Sep 18, 2018 at 4:01
  • No, I want to get several arrays as a result Commented Sep 18, 2018 at 4:02
  • Also, it would be best to stick to loops for performance that is. Commented Sep 18, 2018 at 4:04
  • Please share the code what have you tried so far? Commented Sep 18, 2018 at 4:12
  • And clear your intension of output... U just wanted to Print these sub arrays OR returning these many sub arrays from function Commented Sep 18, 2018 at 4:14

1 Answer 1

1
import numpy as np
A = np.asarray([0, 2, 7, 9, 13])    
x = 2
np.split(A, range(x, len(A), x))  
# [array([0, 2]), array([7, 9]), array([13])]

Note that as @Divakar mentioned in his comment, you are better off performance wise using loops (or in this case a list comprehension).

def f(seq, n):
    return [seq[i:min(i + n, len(seq))] for i in range(0, len(seq), n)]

def g(seq, n):
    return np.split(seq, range(n, len(A), n))

%timeit f(range(12345), 109)
65.2µs ± 468ns (mean +- std. dev. of 7 runs, 10000 loops each)

%timeit g(range(12345), 109)
1.32ms ± 5.21 µs (mean +- std. dev. of 7 runs, 10000 loops each)

Edit

Since slicing past the last index will naturally slice till the last element, we can do away with the check

def f(seq, n):
    return [seq[i : i + n] for i in range(0, len(seq), n)]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.