0

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
>>> 

1 Answer 1

1

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]))
Sign up to request clarification or add additional context in comments.

1 Comment

can you explain why ?

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.