6

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?

1
  • Why? What's wrong with using plain a.T? Commented Aug 27, 2016 at 21:53

4 Answers 4

7

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)

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

Comments

4

Here is one way:

In [20]: list(a.T)
Out[20]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])]

Here is another one:

In [40]: [*map(np.ravel, np.hsplit(a, 3))]
Out[40]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])]

Comments

2

Simply call the list function:

list(a.T)

Comments

1

Well, here's another way. (I assume x is your original 2d array.)

[row for row in x.T]

Still uses a Python list generator expression, however.

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.