18

How can I split an array's columns into three arrays x, y, z without manually writing each of the [:,0],[:,1],[:,2] separately?

Example

# Create example np array
import numpy as np
data = np.array([[1,2,3],[4,5,6],[7,8,9]])

Now data is

[[1 2 3]
 [4 5 6]
 [7 8 9]]

What I want to do:

x, y, z = data[:,0], data[:,1], data[:,2] ## Help me here!
print(x)

Wanted output:

array([1, 4, 7])

2 Answers 2

32

Transpose, then unpack:

>>> x, y, z = data.T
>>> x
array([1, 4, 7])
Sign up to request clarification or add additional context in comments.

Comments

5

You don't need to slice it.

>>> import numpy as np
>>> data = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> x, y, z = data.T
>>> x
array([1, 4, 7])
>>> y
array([2, 5, 8])
>>> z
array([3, 6, 9])

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.