user3378649
user3378649

Reputation: 5354

How can I split numpy array

How can I split an array in numpy, why I am getting this error ?

>>> import numpy as np
>>> d= np.array(range(10),np.float32)
>>> b, a = d[:3,:], d[3:,:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> 

Upvotes: 0

Views: 415

Answers (1)

Akavall
Akavall

Reputation: 86306

Your array d is one dimensional; however when you do d[3:,:] you are specifying two dimensions. Hence the error: IndexError: too many indices for array.

Here is the code that gives you the result you are looking for:

In [6]: b,a = d[:3], d[3:]

In [7]: b
Out[7]: array([ 0.,  1.,  2.], dtype=float32)

In [8]: a
Out[8]: array([ 3.,  4.,  5.,  6.,  7.,  8.,  9.], dtype=float32)

Another option is:

In [4]: b,a = tuple(np.split(d, [3]))

Upvotes: 1

Related Questions