Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting columns of a numpy array easily

Tags:

python

numpy

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])
like image 519
Roman Avatar asked Jun 13 '15 16:06

Roman


People also ask

How do I split a NumPy array vertically?

NumPy: vsplit() function The vsplit() function is used to split an array into multiple sub-arrays vertically (row-wise). Note: vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension.

How does NumPy split work?

NumPy: split() function The split() function is used assemble an nd-array from given nested lists of splits. Array to be divided into sub-arrays. If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.


1 Answers

Transpose, then unpack:

>>> x, y, z = data.T
>>> x
array([1, 4, 7])
like image 63
behzad.nouri Avatar answered Sep 28 '22 03:09

behzad.nouri