+4 votes
in Programming Languages by (77.2k points)
How can I convert a 2D Python list to a Numpy matrix?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

There are several ways to convert a 2D list to a numpy matrix:

  • using numpy.array()
  • using numpy.matrix()
  • using numpy.asmatrix()

Here are examples:

>>> a=[[1,2,3],[4,5,6]]
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> np.array(a)
array([[1, 2, 3],
       [4, 5, 6]])
>>> b=np.array(a)
>>> b
array([[1, 2, 3],
       [4, 5, 6]])
>>> c=np.matrix(a)
>>> c
matrix([[1, 2, 3],
        [4, 5, 6]])
>>> d=np.asmatrix(a)
>>> d
matrix([[1, 2, 3],
        [4, 5, 6]])


...