read a matrix from a text file into numpy

If I read in your text file correctly, you can read in the file using pandas with space delimiter:

import pandas as pd
import numpy as np
dat = pd.read_csv("test.txt",index_col=0,delimiter='\s+').to_numpy()

Looks like this:

array([[-0.  ,  0.09,  0.03, -0.27, -0.28,  0.83, -0.31],
       [ 0.09,  0.03, -0.26, -0.28,  0.83, -0.31,   nan],
       [ 0.  ,  0.11,  0.11,  0.33,  0.1 ,   nan,   nan],
       [ 0.03,  0.03, -0.  ,  0.03,   nan,   nan,   nan],
       [-0.02,  0.91, -0.04,   nan,   nan,   nan,   nan],
       [ 0.92, -0.03,   nan,   nan,   nan,   nan,   nan],
       [ 0.91,   nan,   nan,   nan,   nan,   nan,   nan]])

So we just need to invert the nan:

idx = np.arange(dat.shape[1])
arr = np.empty(dat.shape)
for i in range(dat.shape[1]):
    arr[i] = dat[i][np.concatenate([idx[-i:],idx[:-i]])]

And the end result looks like this:

arr

array([[-0.  ,  0.09,  0.03, -0.27, -0.28,  0.83, -0.31],
       [  nan,  0.09,  0.03, -0.26, -0.28,  0.83, -0.31],
       [  nan,   nan,  0.  ,  0.11,  0.11,  0.33,  0.1 ],
       [  nan,   nan,   nan,  0.03,  0.03, -0.  ,  0.03],
       [  nan,   nan,   nan,   nan, -0.02,  0.91, -0.04],
       [  nan,   nan,   nan,   nan,   nan,  0.92, -0.03],
       [  nan,   nan,   nan,   nan,   nan,   nan,  0.91]])

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top