idude
idude

Reputation: 4912

How to split my numpy array

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!

Upvotes: 1

Views: 118

Answers (2)

Statham
Statham

Reputation: 4118

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

Upvotes: 1

James
James

Reputation: 36598

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.

Upvotes: 3

Related Questions