How can I use numpy.genfromtxt to read the lower triagular matrix into a numpy array?

I have a bottom diagonal matrix like this

1
2 3
4 5 6

      

in a text file and I want to read it into a numpy array with zeros above the main diagonal. The simplest code I can think of

import io
import scipy

data = "1\n2 3\n4 5 6"
scipy.genfromtxt(io.BytesIO(data.encode()))

      

doesn't work with

ValueError: Some errors were detected !
    Line #2 (got 2 columns instead of 1)
    Line #3 (got 3 columns instead of 1)

      

which makes sense because there is nothing in the text file at the top diagonal of the matrix, so numpy doesn't know what to interpret as missing values.

Looking at the documentation , I want something like a parameter invalid_raise = False

, except that I don't want to skip the "invalid" lines,


With some changes below, the last code I am using is

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()

      

+3


source to share


1 answer


np.tril_indices_from()

makes it easy to populate the bottom triagular matrix of an array using fancy idexing:



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.]])

      

+2


source







All Articles