Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make List from Numpy Matrix in Python

I using the dot() function from numpy to multiply a matrix of 3x3 with a numpy.array of 1x3. The output is for example this:

[[ 0.16666667 0.66666667 0.16666667]]

which is of type:

<class 'numpy.matrixlib.defmatrix.matrix'> 

how can I convert this to a list. Because I know the result will always be a matrix of 1x3 so it should be coverted to a list because I need to be able to loop through it later for calculation the pearson distance of two of those lists.

So to summarize: how can I make a list from this matrix?

like image 579
Javaaaa Avatar asked Mar 03 '11 16:03

Javaaaa


People also ask

How do I create a NumPy list?

You can also create a Python list and pass its variable name to create a Numpy array. You can confirm that both the variables, array and list , are a of type Python list and Numpy array respectively. To create a two-dimensional array, pass a sequence of lists to the array function.


2 Answers

May not be the optimal way to do this but the following works:

a = numpy.matrix([[ 0.16666667, 0.66666667, 0.16666667]]) list(numpy.array(a).reshape(-1,)) 

or

numpy.array(a).reshape(-1,).tolist() 

or

numpy.array(a)[0].tolist() 
like image 183
JoshAdel Avatar answered Sep 22 '22 20:09

JoshAdel


Use the tolist() method on the matrix object :

>>> import numpy >>> m = numpy.matrix([1, 2, 3]) >>> type(m) <class 'numpy.core.defmatrix.matrix'> >>> m.tolist() [[1, 2, 3]] 
like image 40
tito Avatar answered Sep 21 '22 20:09

tito