Transforming a list to a column vector in Python

前端 未结 4 1981
面向向阳花
面向向阳花 2021-01-21 05:33

I was wondering if there\'s a function that takes a list X as input and outputs a column vector corresponding to X?

(I looked around and I susp

4条回答
  •  爱一瞬间的悲伤
    2021-01-21 05:41

    If you want to convert a Python list into a numpy column vector, you can use the ndmin argument to the array conductor:

    col_vec = np.array(X, ndmin=2)
    

    Simply constructing an array will give you a 1D array, which can not be directly transposed:

    a = np.array(X)
    a is a.T
    

    There are a couple of ways to transform a 1D vector into a column though:

    col_vec = a.reshape(-1, 1)
    

    and

    col_vec = a[np.newaxis, :]
    

    are fairly common idioms after your list is already an array.

    col_vec = np.reshape(X, (-1, 1))
    

    and

    col_vec = np.expand_dims(X, -1)
    

    will work even on a raw list.

    P.S. Stay away from np.matrix it's very outdated and limited, if not outright deprecated.

提交回复
热议问题