1

So I'm pretty new to numpy, and I'm trying working on a project, but have encountered an error that I can't seem to solve.

Imagine we had an NDarray in the following format

[4,5,6,1]
[3,5,2,0]
[4,7,3,1]

How would I split it into two parts such that the first part is:

[4,5,6]
[3,5,2]
[4,7,3]

and the second part is

[1,0,1]

I know the solution must be pretty simple but I can't seem to figure it out

Thanks in advance!

2 Answers 2

3

Try:

a = np.array([[4,5,6,1],
              [3,5,2,0],
              [4,7,3,1]])

b,c = a[:,:-1], a[:,-1]

This uses numpy's slicing to keep all rows and split the columns on the last one.

Sign up to request clarification or add additional context in comments.

Comments

1
>>> import numpy as np
>>> a=np.array([[4,5,6,1],[3,5,2,0],[4,7,3,1]])
>>> a
array([[4, 5, 6, 1],
       [3, 5, 2, 0],
       [4, 7, 3, 1]])
>>> b=a[:,0:3]
>>> b
array([[4, 5, 6],
       [3, 5, 2],
       [4, 7, 3]])
>>> c=a[:,3]
>>> c
array([1, 0, 1])
>>>

This is something called array slice in python, not too much about numpy.

For more details about array slice, see Explain Python's slice notation

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.