Creating a list from a Scipy matrix
This is my first post and I'm still a Python and Scipy newcomer, so go easy on me! I'm trying to convert an Nx1 matrix into a python list. Say I have some 3x1 matrix
x = scipy.matrix([1,2,3]).transpose()
My aim is to create a list, y, from x so that
y = [1, 2, 3]
I've tried using the tolist()
method, but it returns [[1], [2], [3]]
, which isn't the result that I'm after. The best i can do is this
y = [xi for xi in x.flat]
but it's a bit cumbersome, and I'm not sure if there's an easier way to achieve the same result. Like I said, I'm still coming to grips with Python and Scipy开发者_JAVA百科...
Thanks
A question for your question
While Sven and Navi have answered your question on how to convert
x = scipy.matrix([1,2,3]).transpose()
into a list, I'll ask a question before answering:
- Why are you using an Nx1 matrix instead of an array?
Using array instead of matrix
If you look at the Numpy for Matlab Users wiki/documentation page, section 3 discusses 'array' or 'matrix'? Which should I use?. The short answer is that you should use array.
One of the advantages of using an array is that:
You can treat rank-1 arrays as either row or column vectors. dot(A,v) treats v as a column vector, while dot(v,A) treats v as a row vector. This can save you having to type a lot of transposes.
Also, as stated in the Numpy Reference Documentation, "Matrix objects are always two-dimensional." This is why x.tolist()
returned a nested list of [[1], [2], [3]]
for you.
Since you want an Nx1 object, I'd recommend using array as follows:
>>> import scipy
>>> x = scipy.array([1,2,3])
>>> x
array([1, 2, 3])
>>> y = x.tolist() // That's it. A clean, succinct conversion to a list.
>>> y
[1, 2, 3]
If you really want to use matrix
If for some reason you truly need/want to use a matrix instead of an array, here's what I would do:
>>> import scipy
>>> x = scipy.matrix([1,2,3]).transpose()
>>> x
matrix([[1],
[2],
[3]])
>>> y = x.T.tolist()[0]
>>> y
[1, 2, 3]
In words, the x.T.tolist()[0]
will:
- Transpose the x matrix using the
.T
attribute - Convert the transposed matrix into a nested list using
.tolist()
- Grab the first element of the nested listed using
[0]
How about
x.ravel().tolist()[0]
or
scipy.array(x).ravel().tolist()
I think you are almost there use the flatten function http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html
精彩评论