Reputation: 1242
I don't understand the rules for accessing elements, rows and columns in a numpy.matrix
. Here is an example:
import numpy as np
m = np.matrix( [ [ 0, 1, 2 ] ] )
print( "m:", m )
print( "m[0]:", m[ 0 ] )
print( "m[0,]", m[ 0, ] )
print( "m[0,:]", m[ 0, : ] )
print( "m[0,i]", m[ 0, 0 ], m[ 0 , 1 ], m[ 0, 2 ] )
and here's what it prints:
m: [[0 1 2]]
m[0]: [[0 1 2]]
m[0,] [[0 1 2]]
m[0,:] [[0 1 2]]
m[0,i] 0 1 2
It seems that numpy.matrix
works differently than numpy.array
or Python 2D lists. Can someone point to a succinct explanation of how indexing works for numpy.matrix
? And, is there any more succinct way than the last line of code to extract all the elements of a (1,n) numpy.matrix
as if it were a 1D container?
Upvotes: 0
Views: 120
Reputation: 231395
A matrix is always 2d. Row indexing (which most of your examples are doing) still returns a 2d array.
In [1]: m = np.matrix([[ 0,1,2]])
In [2]: m
Out[2]: matrix([[0, 1, 2]])
In [3]: m[0]
Out[3]: matrix([[0, 1, 2]]) # note the 'matrix' display
indexing an element:
In [4]: m[0,1]
Out[4]: 1
matrix as regular array:
In [6]: m.A
Out[6]: array([[0, 1, 2]]) # still 2d
as list:
In [7]: m.tolist()
Out[7]: [[0, 1, 2]]
m
as 1d array:
In [8]: m.A1
Out[8]: array([0, 1, 2]) # in effect m.A.ravel()
You don't have to use np.matrix
, especially if it's confusing. It's in the process of being deprecated.
Upvotes: 1