稀疏矩阵输出到 csv

Sparse matrix output to csv

我有一个稀疏矩阵 z,它是 scipy.sparse.csr_matrix,形状 (n,m),其中 n<<m。我也有标签 l,它只是一个 np.array 的字符串,大小为 n.

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

现在我正在做

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

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

示例:

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,
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 是一种遍历多个列表的简单方法,使用最长的作为参考。