Transforming a row vector into a column vector in Numpy

后端 未结 4 1223
深忆病人
深忆病人 2020-12-09 09:46

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?

4条回答
  •  忘掉有多难
    2020-12-09 10:51

    This one is a really good question.

    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 does not modify the original array.

提交回复
热议问题