Reputation: 123
I have an MxN numpy matrix and would like to make it into a one dimensional vector that just stacks each row after another. Essentially something like this...
[x11, x12 ... x1m
x21, x22 ... x2m
.
.
xn1, xn2 ... xnm]
Goes to this...
[x11, x12 ... x1m, x21, x22 ... x2m ... xn1, xn2 ... xnm]
What is the best/ most efficient way to do this?
Upvotes: 1
Views: 157
Reputation: 4824
You could also .reshape()
, although this method demands that you know the destination shape (for at least all but one axis) of your output array.
>>> import numpy as np
>>> foo = np.array([[1, 2, 3], [4, 5, 6]])
>>> foo.reshape(1, 6)
array([[1, 2, 3, 4, 5, 6]])
compare to:
>>> foo.reshape(-1, 1)
array([[1],
[2],
[3],
[4],
[5],
[6]])
Upvotes: 0
Reputation: 1406
You could you .ravel
From the docs:
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print np.ravel(x)
[1 2 3 4 5 6]
Upvotes: 4