Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy array.tolist()和scipy.sparse tolist()之间的区别是什么_Python_Numpy_Scipy - Fatal编程技术网

Python numpy array.tolist()和scipy.sparse tolist()之间的区别是什么

Python numpy array.tolist()和scipy.sparse tolist()之间的区别是什么,python,numpy,scipy,Python,Numpy,Scipy,使用numpy我得到 import numpy as np from scipy.sparse import lil_matrix 将测试列表作为包含6个元素的列表提供。但是当我使用scipy.sparse时 test_mat = (np.ones((4,6))) test_list = test_mat[0,:].tolist() 将test\u list作为一个包含一个元素的列表,该列表依次包含6个元素(test\u list[0]包含6个元素) 有人能给我解释一下导致这种差异的潜在机制

使用numpy我得到

import numpy as np
from scipy.sparse import lil_matrix
将测试列表作为包含6个元素的列表提供。但是当我使用scipy.sparse时

test_mat = (np.ones((4,6)))
test_list = test_mat[0,:].tolist()
test\u list
作为一个包含一个元素的列表,该列表依次包含6个元素(
test\u list[0]
包含6个元素)

有人能给我解释一下导致这种差异的潜在机制吗?
感谢这是因为
lil_matrix.todense()
返回一个numpy
matrix
,它始终具有
ndim=2
,而不是numpy
ndarray
,当在切片中仅选择一行/列时,它将降低其维度。矩阵/数组的维数在转换为列表格式时保留

要查看阵列中的二维行为,请将其切片为:

test_mat = lil_matrix(np.ones((4,6)))
test_list = test_mat[0,:].todense().tolist()
或者,通过以下方式启动:

test_mat = np.ones((4,6))
test_list = test_mat[0:1,:].tolist()
您将看到2d列表,就像您从
lil\u矩阵中看到的一样

以下是您在转换为列表之前拥有的内容:

test_mat = np.matrix(np.ones((4,6)))
test_list = test_mat[0:1,:].tolist()
使用不减少维度的切片:

In [137]: ma = np.ones((4,6))

In [138]: mm = np.matrix(np.ones((4,6)))

In [139]: ms = lil_matrix(np.ones((4,6)))

In [141]: ma[0,:]
Out[141]: array([ 1.,  1.,  1.,  1.,  1.,  1.])

In [142]: mm[0,:]
Out[142]: matrix([[ 1.,  1.,  1.,  1.,  1.,  1.]])

In [143]: ms[0,:].todense()
Out[143]: matrix([[ 1.,  1.,  1.,  1.,  1.,  1.]])
上面方括号的数量是关键。看看它们的形状:

In [144]: ma[0:1,:]
Out[144]: array([[ 1.,  1.,  1.,  1.,  1.,  1.]])

这是实施
阵列
和密集矩阵的结果: 当您索引
数组时,如中所示

In [145]: ma[0:1,:].shape
Out[145]: (1, 6)

In [146]: ma[0,:].shape
Out[146]: (6,)

In [147]: mm[0,:].shape
Out[147]: (1, 6)

In [148]: ms[0,:].shape
Out[148]: (1, 6)
你需要一个新的1D阵列

但是,在稀疏矩阵上执行相同的索引时,结果是1x6稀疏矩阵。请注意,这仍然是一个二维矩阵,其中一个维度的长度恰好为1

由于
tolist()
返回一个表示矩阵的列表,因此可以得到从
数组中获得的1D对象的简单列表以及包含稀疏矩阵行的2D“列表列表”

test_list = test_mat[0,:]