首页 > 解决方案 > 稀疏矩阵输出到 csv

问题描述

我有一个稀疏矩阵z,它是 ascipy.sparse.csr_matrix并且形状为(n,m)where n<<m。我也有标签l,它只是一个np.array带有 size 的字符串n

我想做的是用“参差不齐”的数据版本制作一个 csv 文件。即,所有非零值都z[0]将进入带有标题值的 csv 文件的列中l[0],但每列将具有不同数量的值。不幸的是numpy,不能很好地处理参差不齐的数组,我不确定什么是构建它的优雅方式。

现在我只是在做

np.savetxt(pth, z.todense().T, delimiter = ",")

并手动添加列标题,因为我的下一个处理步骤可以处理所有的零,但这样很慢。

例子:

z.todense()
array([[0,0,1,0,0,-1,0,3,0,-6,4],
       [-1,0,4,0,0,0,0,0,0,0,-2]])

l
array(["chan1", "chan2"])

我想要的是

example.csv

chan1, chan2
1,-1
-1,4
3,-2
-6,
4,

标签: csvnumpysparse-matrix

解决方案


In [74]: from scipy import sparse

In [75]: M = sparse.csr_matrix([[0,0,1,0,0,-1,0,3,0,-6,4],
    ...:        [-1,0,4,0,0,0,0,0,0,0,-2]])
In [76]: M
Out[76]: 
<2x11 sparse matrix of type '<class 'numpy.int64'>'
    with 8 stored elements in Compressed Sparse Row format>

In [77]: M.A
Out[77]: 
array([[ 0,  0,  1,  0,  0, -1,  0,  3,  0, -6,  4],
       [-1,  0,  4,  0,  0,  0,  0,  0,  0,  0, -2]], dtype=int64)

lil格式按行给出数据:

In [78]: Ml = M.tolil()
In [79]: Ml.data
Out[79]: array([list([1, -1, 3, -6, 4]), list([-1, 4, -2])], dtype=object)

现在只需按照您想要的方式将这些列表写入文件即可:

In [81]: from itertools import zip_longest

In [82]: for i,j in zip_longest(*Ml.data, fillvalue=''):
    ...:     astr = '%s, %s'%(i,j)
    ...:     print(astr)
    ...:     
1, -1
-1, 4
3, -2
-6, 
4, 

zip_longest是一种简单的方法来遍历多个列表,使用最长的作为参考。


推荐阅读