2012年12月21日 星期五

[ Python 常見問題 ] How to make List from Numpy Matrix in Python


來源自 這裡
Question:
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:
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?

Answer:
May not be the optimal way to do this but the following works:
  1. a = numpy.matrix([[ 0.166666670.666666670.16666667]])  
  2. list(numpy.array(a).reshape(-1,))  
or
  1. numpy.array(a).reshape(-1,).tolist()  
or
  1. numpy.array(a)[0].tolist()  
or
  1. numpy.array(a).flatten().tolist()  
This message was edited 1 time. Last update was at 22/12/2012 10:44:48

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...