【发布时间】:2015-05-11 22:47:00
【问题描述】:
我有一个像这样的下对角矩阵
1
2 3
4 5 6
在一个文本文件中,我想将它读入一个主对角线上方为零的 numpy 数组。我能想到的最简单的代码
import io
import scipy
data = "1\n2 3\n4 5 6"
scipy.genfromtxt(io.BytesIO(data.encode()))
失败了
ValueError: Some errors were detected !
Line #2 (got 2 columns instead of 1)
Line #3 (got 3 columns instead of 1)
这是有道理的,因为在文本文件中,矩阵的上对角线部分没有 任何东西,因此 numpy 不知道将什么解释为缺失值。
查看documentation,我想要invalid_raise = False 之类的选项,但我不想跳过“无效”行。
通过对下面答案的一些修改,我使用的最终代码是
import scipy
with open("data.txt", "r") as r:
data = r.read()
n = data.count("\n") + 1
mat = scipy.zeros((n, n))
mat[scipy.tril_indices_from(mat)] = data.split()
【问题讨论】:
标签: python arrays numpy matrix