csv - 稀疏矩阵输出到 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,
解决方案
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
是一种简单的方法来遍历多个列表,使用最长的作为参考。
推荐阅读
- python - Tensorflow:对张量进行分桶,然后产生分类张量
- c# - 对数据库中非空列的查询排序
- python-3.x - anaconda 上的 jupyter 笔记本 - “win32security”内核错误
- python - 如何使用python从块中索引整个矩阵
- java - 未能在项目 blazegraph-service 上执行目标:
- git - git config --global 或 git push 不起作用。Bitbucket 相关
- php - 使用 SetAutoPageBreak 多单元格值分页后的 FPDF 未插入到定义的 Y 位置
- python - 如何提高检查 10M 行数据框中每一行的条件的性能?
- tensorflow - 贝叶斯模型不使用 tensorflow 概率和 keras 进行学习
- javascript - 如何在 Google Apps 脚本中引用数组中的元素