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

1 Answer

0 votes
by (25.1k points)

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]])

...