python – numpy array.tolist()和scipy.sparse tolist()之间有什么区别

weixin_38049686 2019-09-12 12:31:47
import numpy as np from scipy.sparse import lil_matrix 使用numpy我得到 test_mat = (np.ones((4,6))) test_list = test_mat[0,:].tolist() 将test_list作为包含6个元素的列表.但是,我使用scipy.sparse test_mat = lil_matrix(np.ones((4,6))) test_list = test_mat[0,:].todense().tolist() 将test_list作为一个列表,其中包含一个元素,而该元素又有6个元素(test_list [0]有6个元素). 有人可以向我解释导致这种差异的潜在机制吗?谢谢
...全文
115 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38067747 2019-09-12
  • 打赏
  • 举报
回复
这是因为lil_matrix.todense()返回一个numpy矩阵,它总是有ndim = 2,而不是numpy ndarray,当切片中只选择了一行/ col时,它会减小它的尺寸.矩阵/数组的维度在转换为列表列表格式时保留. 要查看数组中的2d行为,请将其切片为: test_mat = np.ones((4,6)) test_list = test_mat[0:1,:].tolist() 或者,将其启动为: test_mat = np.matrix(np.ones((4,6))) test_list = test_mat[0:1,:].tolist() 您将从lil_matrix中看到2d列表列表 这是您转换为列表之前的所有内容: 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)

476

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧