2

How to stack all columns in a 2-dimensional Numpy array into a 1-dimensional array.

I.e. I have:

x = np.array([[1, 3, 5],[2, 4, 6]])

And I want to get:

np.array([1, 2, 3, 4, 5, 6])

Is there a way to achieve this without a loop or list comprehension?

3
  • y before the loop is float dtype Commented Sep 3, 2018 at 20:21
  • A simpler way to do your concatenate: np.concatenate([x[:,i] for i in range(3)]) Commented Sep 3, 2018 at 21:02
  • thanks - updated (both list comprehension and float dtype) - though obviously key element of the question is unchanged and the accepted answer is superior in my view Commented Jan 7, 2019 at 14:56

2 Answers 2

4

You can use ravel:

x = np.array([[1, 3, 5],[2, 4, 6]])

res = x.ravel('F')  # or x.T.ravel()

# array([1, 2, 3, 4, 5, 6])
Sign up to request clarification or add additional context in comments.

Comments

4

Using flatten with 'F'

x.flatten('F')
Out[114]: array([1, 2, 3, 4, 5, 6])

2 Comments

Nice! Never knew about 'F'. Have stolen it, it works just as well with ravel.
@jpp yep :-) it is :-)

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.