你好,所以python社区
我有一个关于numpy稀疏矩阵COO格式的问题。具体如下:
我有一个csv
文件,有4列a
,b
,c
,d
,我需要从这个csv文件中形成SciPy COO_矩阵,但是我需要能够在SciPy稀疏矩阵中保持条目的插入顺序。目前,我的数据是按列d
排序的,最后在矩阵中,我也希望保留这个顺序。目前,我是这样做的:
def _build_interaction_matrix(rows, cols, data, score):
mat = sp.lil_matrix((rows, cols), dtype=np.int32)
for a, b, c, d in data:
mat[a, b] = 1.0
return mat.tocoo()
现在当我打电话给:
^{pr2}$顺序丢失了,我得到了a
的顺序,然后是b
。有没有一种方法可以按键d
对矩阵排序,这样我仍然返回一个以a
和{d
排序的COO矩阵吗?在
编辑:最终目标是能够通过保持顺序迭代地构建矩阵,然后将其转换为COO
。我需要迭代地执行它,因为在循环中需要检查列c
上存在一个条件。在
Edit2:我还需要实现COO.getrow(row_index)
,它保留了row_index
列索引的原始顺序
对于编辑2
我能想到的最好办法是:
def get_all_items(uid, pid, u):
init = 0
indices = np.argsort(uid, kind='mergesort')
for i in range(len(indices)):
if (uid[indices[i]] == u and init == 0):
start = i
init = 1
if(i >= 1 and uid[indices[i-1]] ==u and uid[indices[i]] != u):
end = i
idex = indices[start:end]
if len(idex) != 0:
return pid[idex]
谢谢你对解决这个问题的建议,如果你需要更多的信息,请告诉我。在
如果您直接以
coo
格式创建矩阵,则至少在初始阶段保持了顺序:实际上,row和col属性将是输入数组(前提是它们兼容):
^{pr2}$但是这个命令很容易丢失。例如,通过
csr
格式(在大多数计算中使用)的往返结束时,按行排序,然后按列排序如果有重复的点,它们被相加
对于转换为
lil
:rows
按定义是按行排序的,但在一行中它不必是sort。在{sort with first^执行词法排序
迭代生成
lil
不会保留任何“顺序”信息:getrow公司
getrow
不进行排序可能比我最初想象的要简单:制作随机矩阵:
行数为10的元素:
对应的列值(不排序)
与使用csr格式的
getrow
进行比较:还有通过利尔
相关问题 更多 >
编程相关推荐