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
I don't think there is a function, but there is a dedicated object, np.c_
>>> X = list('hello world')
>>> X
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
np.c_[X]
array([['h'],
['e'],
['l'],
['l'],
['o'],
[' '],
['w'],
['o'],
['r'],
['l'],
['d']], dtype='<U1')
You can also do (note the extra square brackets)
>>> np.array([X]).T
A list is a native type of Python, whereas a numpy array is a numpy object. You will need to convert your list to a numpy array first. You can do something like the following.
x = list(range(5))
print(x)
[0, 1, 2, 3, 4]
x_vector = np.asarray(x)
array([0, 1, 2, 3, 4])
Now, Python does not know whats the difference between a row vector and a column vector, that is up to how you will use the vector. The current vector is 1x5. If you want 5x1, you can take the transpose by either
x_vector.T
or
np.transpose(x_vector)
However, since this is a 1D matrix, the transpose is the same as the non-transposed vector in memory.
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.
similar but different:
mylist=[2,3,4,5,6]
method1:
np.array([[i] for i in mylist])
output:
array([[2],
[3],
[4],
[5],
[6]])
method 2:
np.array(mylist).reshape(len(mylist),1)
output:
array([[2],
[3],
[4],
[5],
[6]])