扩展(添加行或列)scipy.sparse矩阵 [英] expanding (adding a row or column) a scipy.sparse matrix

查看:120
本文介绍了扩展(添加行或列)scipy.sparse矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个来自scipy.sparse的NxN矩阵M(lil_matrix或csr_matrix),并且我想使其为(N + 1)xN,其中M_modified [i,j] = M [i,j]为0 <=我< N(和所有j)和M [N,j] = 0对于所有j.基本上,我想在M的底部添加一行零,并保留矩阵的其余部分.有没有复制数据的方法吗?

Suppose I have a NxN matrix M (lil_matrix or csr_matrix) from scipy.sparse, and I want to make it (N+1)xN where M_modified[i,j] = M[i,j] for 0 <= i < N (and all j) and M[N,j] = 0 for all j. Basically, I want to add a row of zeros to the bottom of M and preserve the remainder of the matrix. Is there a way to do this without copying the data?

推荐答案

我认为没有任何方法可以真正避免进行复制.这两种类型的稀疏矩阵都将它们的数据存储为Numpy数组(在csr的data和index属性中以及lil的data和rows属性中)内部存储,并且Numpy数组无法扩展.

I don't think that there is any way to really escape from doing the copying. Both of those types of sparse matrices store their data as Numpy arrays (in the data and indices attributes for csr and in the data and rows attributes for lil) internally and Numpy arrays can't be extended.

更新以获取更多信息:

LIL确实代表LInked List,但是当前的实现并不完全符合该名称.用于datarows的Numpy数组都是对象类型.这些数组中的每个对象实际上都是Python列表(当所有值连续为零时为空列表). Python列表不是完全链接的列表,但是由于O(1)查找,它们是很接近的并且坦率地说是更好的选择.就个人而言,我没有立即看到在这里使用Numpy对象数组而不是仅使用Python列表的意义.您可以相当容易地将当前的lil实现更改为使用Python列表,从而无需添加整个矩阵即可添加一行.

LIL does stand for LInked List, but the current implementation doesn't quite live up to the name. The Numpy arrays used for data and rows are both of type object. Each of the objects in these arrays are actually Python lists (an empty list when all values are zero in a row). Python lists aren't exactly linked lists, but they are kind of close and quite frankly a better choice due to O(1) look-up. Personally, I don't immediately see the point of using a Numpy array of objects here rather than just a Python list. You could fairly easily change the current lil implementation to use Python lists instead which would allow you to add a row without copying the whole matrix.

这篇关于扩展(添加行或列)scipy.sparse矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆