Reputation: 211
Say I have the following array:
a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);
How can I stack the columns on top of each other to form a single column vector to produce the following?
b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);
Upvotes: 2
Views: 609
Reputation: 18638
The shortest is a.T.reshape(-1,1)
:
a.T
for the good layout, reshape
for the good shape, with one column.or equivalent : a.reshape(-1,1,order='F')
.
Upvotes: 0
Reputation: 231395
To stick with the stacking idea, a list of a.T
is:
In [87]: list(a.T)
Out[87]:
[array([1, 3, 1]),
array([3, 2, 7]),
array([5, 5, 3]),
array([2, 6, 6]),
array([3, 7, 5])]
which can then be concatenated on the one axis
In [90]: np.concatenate(a.T)
Out[90]: array([1, 3, 1, 3, 2, 7, 5, 5, 3, 2, 6, 6, 3, 7, 5])
And turn it into a column vector by adding a dimension:
In [91]: _[:,None]
Out[91]:
array([[1],
[3],
[1],
[3],
[2],
[7],
[5],
[5],
[3],
[2],
[6],
[6],
[3],
[7],
[5]])
It may be worth noting that a.T
, the transpose, is produced by changing the order to F
. So this is a variation on the a.ravel(order='F')
approach. In order to stack the columns it has to reorder the elements of the array (default is 'c' row oriented).
Upvotes: 0
Reputation: 53029
You can use 'F'
for Fortran order together with ravel
or reshape
:
a.ravel('F')[:, None]
# array([[1],
# [3],
# [1],
# [3],
# [2],
# ...
Upvotes: 1
Reputation: 78690
You can flatten the transposed array, create a new axis, and transpose again.
>>> np.ravel(a.T)[None].T
array([[1],
[3],
[1],
[3],
[2],
[7],
[5],
[5],
[3],
[2],
[6],
[6],
[3],
[7],
[5]])
Upvotes: 1
Reputation: 11717
You can use reshape function and the transpose .T
operator
np.reshape(a.T, (a.size,1))
Upvotes: 1