Constructing a matrix column by column

``````>>> vec1 = np.random.rand(2)
>>> vec1
array([0.41775268, 0.22867214])
>>> vec2 = np.random.rand(2)
>>> np.array([vec1, vec2])
array([[0.41775268, 0.22867214],
[0.38311297, 0.62432934]])
>>> np.array([vec1 vec2])
File "<stdin>", line 1
np.array([vec1 vec2])
^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
>>> np.array([vec1; vec2])
File "<stdin>", line 1
np.array([vec1; vec2])
^
SyntaxError: invalid syntax
>>> np.array([vec1, vec2])
array([[0.41775268, 0.22867214],
[0.38311297, 0.62432934]])
``````

Here it seems that the vectors ‘vec1’ and ‘vec2’ are treated as row-vectors, and they are stacked vertically to form a matrix.

What if we want to treat them as column-vectors, and put them side by side horizontallly?

Take a look at `numpy.stack`.

``````>>> import numpy as np
>>> vec1 = np.arange(3)
>>> vec2 = np.arange(10, 13)
>>> np.stack([vec1, vec2], axis=1)
array([[ 0, 10],
[ 1, 11],
[ 2, 12]])
``````

There’s also `np.column_stack`:

``````>>> np.column_stack([vec1, vec2])
array([[ 0, 10],
[ 1, 11],
[ 2, 12]])
``````
2 Likes

If you already have a two-dimensional Numpy array that is the “wrong way around”, you can simply transpose it:

``````>>> import numpy as np
>>> vec1, vec2 = np.random.rand(2), np.random.rand(2)
>>> vec1
array([0.11395271, 0.2284228 ])
>>> vec2
array([0.4743048, 0.9649466])
>>> arr = np.array([vec1, vec2])
>>> arr
array([[0.11395271, 0.2284228 ],
[0.4743048 , 0.9649466 ]])
>>> arr.T
array([[0.11395271, 0.4743048 ],
[0.2284228 , 0.9649466 ]])
``````

This creates a view onto the original array - you can then make a new array copy from that, or overwrite the original data (if it’s square):

``````>>> arr[:] = arr.T
>>> arr
array([[0.11395271, 0.4743048 ],
[0.2284228 , 0.9649466 ]])
>>> # Now that we modified it, 'arr.T' gives the original value again,
>>> # which we can also copy to make a new array object.
>>> arr.T.copy()
array([[0.11395271, 0.2284228 ],
[0.4743048 , 0.9649466 ]])
``````