[英]How to make List from Numpy Matrix in Python
我使用numpy中的dot()函數將3x3的矩陣與1x3的numpy.array相乘。 輸出例如是:
[[0.16666667 0.66666667 0.16666667]]
其類型:
<class 'numpy.matrixlib.defmatrix.matrix'>
我該如何將其轉換為列表。 因為我知道結果將始終是1x3的矩陣所以它應該被轉換為列表,因為我需要能夠稍后循環它以計算其中兩個列表的皮爾遜距離。
總結一下:如何從這個矩陣中制作一個列表?
可能不是最佳方式,但以下工作:
a = numpy.matrix([[ 0.16666667, 0.66666667, 0.16666667]])
list(numpy.array(a).reshape(-1,))
要么
numpy.array(a).reshape(-1,).tolist()
要么
numpy.array(a)[0].tolist()
如果a
是你的矩陣,試試吧
a.ravel().tolist()
但是你不需要把它變成一個列表來迭代它。
在矩陣對象上使用tolist()方法:
>>> import numpy
>>> m = numpy.matrix([1, 2, 3])
>>> type(m)
<class 'numpy.core.defmatrix.matrix'>
>>> m.tolist()
[[1, 2, 3]]
其他方式:
>>> import numpy as np
>>> m = np.matrix([1,2,3])
>>> np.array(m).flatten().tolist()
[1,2,3]
嘗試這種簡單的方法。 它適用於1D陣列,不知道具有更高的尺寸。
import mumpy as np # to create a numpy array example
a = np.array([1,2.5,3]) # your 1D numpy array
b = [i for i in a] # your list out of the original numpy array
為什么不簡單:
list(a.flat)
例如:
>>> import numpy as np
>>> a = np.matrix([[ 0.16666667, 0.66666667, 0.16666667]])
>>> a
matrix([[ 0.16666667, 0.66666667, 0.16666667]])
>>> a.flat
<numpy.flatiter object at 0x0000000002DE8CC0>
>>> a.flat.tolist()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.flatiter' object has no attribute 'tolist'
>>> list(a.flat)
[0.16666666999999999, 0.66666667000000002, 0.16666666999999999]
我認為getA1()
可以完成這項工作。
從文檔:
getA1()
把自己當作扁平的ndarray。
相當於np.asarray(x).ravel()
來自https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.getA1.html
m = numpy.matrix([[ 0.16666667, 0.66666667, 0.16666667]])
a = numpy.array(m)[0]
for i in a:
print i
結果是
0.16666667
0.66666667
0.16666667
我來到這里尋找將numpy矩陣轉換為典型2D列表的方法。
對於numpy矩陣m:
my_2d_list = map(list, list(m.A))
如果你只想要1 xn矩陣m的一維列表:
my_1d_list = list(list(m.A)[0])
import numpy as np
a = np.matrix([[1,2,3,4]])
b = map(float, a.transpose())
該代碼段將應用內置函數“漂浮” -它轉換的東西浮點數-到的每一個元素。 由於的第一個元素是一個數組本身,它必須被轉置,從而使每一個數字變成本身的元件。 在這個例子中,a.transpose()等同於np.matrix([[1],[2],[3],[4]])。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.