我有一个像这样的低对角线矩阵
1
2 3
4 5 6在一个文本文件中,我想将它读取到一个numpy数组中,其中0位于主对角线之上。我能想到的最简单的代码
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不知道如何将其解释为缺少的值。
看看文档,我想要类似于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()发布于 2015-05-11 23:12:52
通过花式输入,np.tril_indices_from()可以很容易地填充数组的低三边形矩阵:
data = "1\n2 3\n4 5 6"
n = len(data.split('\n'))
data = data.replace('\n', ' ').split()
a = np.zeros((n, n))
a[np.tril_indices_from(a)] = data
print(a)
#array([[ 1., 0., 0.],
# [ 2., 3., 0.],
# [ 4., 5., 6.]])https://stackoverflow.com/questions/30178871
复制相似问题