Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 2D Numpy array to a list of 1D columns

Tags:

python

numpy

What would be the best way of converting a 2D numpy array into a list of 1D columns?

For instance, for an array:

array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])

I would like to get:

[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])]

This works:

[a[:, i] for i in range(a.shape[1])]

but I was wondering if there is a better solution using pure Numpy functions?

like image 357
Andrzej Pronobis Avatar asked Aug 27 '16 21:08

Andrzej Pronobis


1 Answers

I can't think of any reason you would need

[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])]

Instead of

array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])

Which you can get simply with a.T

If you really need a list, then you can use list(a.T)

like image 117
Eric Avatar answered Sep 30 '22 11:09

Eric