47

Let's say I have a row vector of the shape (1, 256). I want to transform it into a column vector of the shape (256, 1) instead. How would you do it in Numpy?

kmario23
  • 57,311
  • 13
  • 161
  • 150
M.Y. Babt
  • 2,733
  • 7
  • 27
  • 49

6 Answers6

39

you can use the transpose operation to do this:

Example:

In [2]: a = np.array([[1,2], [3,4], [5,6]])
In [5]: a.shape
Out[5]: (3, 2)

In [6]: a_trans = a.T    #or: np.transpose(a), a.transpose()
In [8]: a_trans.shape
Out[8]: (2, 3)
In [7]: a_trans
Out[7]: 
array([[1, 3, 5],
       [2, 4, 6]])

Note that the original array a will still remain unmodified. The transpose operation will just make a copy and transpose it.


If your input array is rather 1D, then you can promote the array to a column vector by introducing a new (singleton) axis as the second dimension. Below is an example:

# 1D array
In [13]: arr = np.arange(6)

# promotion to a column vector (i.e., a 2D array)
In [14]: arr = arr[..., None]    #or: arr = arr[:, np.newaxis]

In [15]: arr
Out[15]: 
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5]])

In [12]: arr.shape
Out[12]: (6, 1)

For the 1D case, yet another option would be to use numpy.atleast_2d() followed by a transpose operation, as suggested by ankostis in the comments.

In [9]: np.atleast_2d(arr).T
Out[9]: 
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5]])
kmario23
  • 57,311
  • 13
  • 161
  • 150
  • 1
    Thanks! I am new to numpy so this is really helpful. – M.Y. Babt Apr 03 '16 at 11:35
  • 10
    For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.), https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ndarray.transpose.html – shinxg Sep 27 '18 at 06:30
  • 3
    Because for 1D array, we have only *one* dimension. There's no transpose defined for such arrays, at least mathematically. – kmario23 Sep 28 '18 at 14:47
  • 1
    For 1D arrays, apply [`np.atleast_2d()`](https://numpy.org/doc/1.18/reference/generated/numpy.atleast_2d.html) and you get the 2D column-vector. – ankostis May 13 '20 at 16:01
  • @ankostis I think this doesn't answer the question, the most likely answer is to use reshape(-1,1) to reshape a 1-D array aka Vector to a single column one. This are the right ones: https://stackoverflow.com/questions/36384760/transforming-a-row-vector-into-a-column-vector-in-numpy/48345638#48345638, https://stackoverflow.com/questions/36384760/transforming-a-row-vector-into-a-column-vector-in-numpy/48365293#48365293 see below. – TassosK Oct 11 '20 at 08:53
  • @TassosK I've added an example for the 1D case. – kmario23 Oct 11 '20 at 10:39
  • 1
    Thank you. You may use `np.atleast_2d()` and then `T`, as suggested in my comment, above. – ankostis Oct 11 '20 at 22:50
30

We can simply use the reshape functionality of numpy:

a=np.array([[1,2,3,4]])
a:
array([[1, 2, 3, 4]])

a.shape
(1,4)
b=a.reshape(-1,1)
b:
array([[1],
       [2],
       [3],
       [4]])

b.shape
(4,1)
Mahdi Ghelichi
  • 1,090
  • 14
  • 23
  • 5
    This would be a much better answer if you could explain what the code does. – Nae Jan 19 '18 at 17:23
  • 1
    See [this answer to the question transpose a 1 dimensional array](https://stackoverflow.com/a/53304024/2641825) "The -1 is a broadcast-like, using all possible elements, and the 1 creates the second required dimension." – Paul Rougieux Feb 13 '20 at 13:32
9

Some of the ways I have compiled to do this are:

>>> import numpy as np
>>> a = np.array([1, 2, 3], [2, 4, 5])
>>> a
array([[1, 2],
       [2, 4],
       [3, 5]])

Another way to do it:

>>> a.T
array([[1, 2],
       [2, 4],
       [3, 5]])

Another way to do this will be:

>>> a.reshape(a.shape[1], a.shape[0])
array([[1, 2],
       [3, 2],
       [4, 5]])

I have used a 2-dimensional array in all of these problems, the real problem arises when there is a 1-dimensional row vector which you want to columnize elegantly.

Numpy's reshape has a functionality where you pass the one of the dimension (number of rows or number of columns) you want, numpy can figure out the other dimension by itself if you pass the other dimension as -1

>>> a.reshape(-1, 1)
array([[1],
       [2],
       [3],
       [2],
       [4],
       [5]])
       
>>> a = np.array([1, 2, 3])
>>> a.reshape(-1, 1)
array([[1],
       [2],
       [3]])
       
>>> a.reshape(2, -1)
...
ValueError: cannot reshape array of size 3 into shape (2,newaxis)

So, you can give your choice of 1-dimension without worrying about the other dimension as long as (m * n) / your_choice is an integer.

If you want to know more about this -1, head over to: What does -1 mean in numpy reshape?

Note: All these operations return a new array and do not modify the original array.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
DuttaA
  • 903
  • 4
  • 10
  • 24
4

You can use reshape() method of numpy object.

To transform any row vector to column vector, use

array.reshape(-1, 1)

To convert any column vector to row vector, use

array.reshape(1, -1)

enter image description here

reshape() is used to change the shape of the matrix. So if you want to create a 2x2 matrix you can call the method like a.reshape(2, 2).

So why this -1 in the answer?

If you dont want to explicitly specify one dimension(or unknown dimension) and wants numpy to find the value for you, you can pass -1 to that dimension. So numpy will automatically calculate the the value for you from the ramaining dimensions. Keep in mind that you can not pass -1 to more than one dimension.

Thus in the first case(array.reshape(-1, 1)) the second dimension(column) is one(1) and the first(row) is unknown(-1). So numpy will figure out how to represent a 1-by-4 to x-by-1 and finds the x for you.

An alternative solutions with reshape method will be a.reshape(a.shape[1], a.shape[0]). Here you are explicitly specifying the diemsions.

Aneesh R S
  • 3,807
  • 4
  • 23
  • 35
4

Using np.newaxis can be a bit counterintuitive. But it is possible.

>>> a = np.array([1,2,3])
>>> a.shape
(3,)
>>> a[:,np.newaxis].shape
(3, 1)
>>> a[:,None]
array([[1],
       [2],
       [3]])

np.newaxis is equal to None internally. So you can use None.
But it is not recommended because it impairs readability

plhn
  • 5,017
  • 4
  • 47
  • 47
1

To convert a row vector into a column vector in Python can be important e.g. to use broadcasting:

import numpy as np

def colvec(rowvec):
    v = np.asarray(rowvec)
    return v.reshape(v.size,1)

colvec([1,2,3]) * [[1,2,3], [4,5,6], [7,8,9]]

Multiplies the first row by 1, the second row by 2 and the third row by 3:

array([[ 1,  2,  3],
       [ 8, 10, 12],
       [  21, 24, 27]])

In contrast, trying to use a column vector typed as matrix:

np.asmatrix([1, 2, 3]).transpose() * [[1,2,3], [4,5,6], [7,8,9]]

fails with error ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0).

Markus Strauss
  • 1,032
  • 11
  • 8