0

I am fairly need to Python and need some help. I am trying to load a txt file and store it as a variable, N where N is supposed to be a square matrix. However, when I tried to check, the ndim() of N is 1 and the number of columns is not equal the number of rows.

I tried the following codes:

N = open('Graph2021.txt', 'r').readlines()
N = np.array(M)

Could someone please help. I have attached a screenshot of part of the txt file to show the breakage of the code to separate the columns (I think).

txt file is filled with zeros and ones:

txt file

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Does this answer your question? [How do I read CSV data into a record array in NumPy?](https://stackoverflow.com/questions/3518778/how-do-i-read-csv-data-into-a-record-array-in-numpy) – Stuart Oct 22 '21 at 08:46

2 Answers2

1

You're reading a file as a list with each element to be a line. However by what you described each line has N element. And surely it must be separated by something (A white space, comma, etc). You have to split your each line by that separator.

with open('Graph2021.txt', 'r') as the_file:
    M = []
    for each_line in the_file:
        M.append(each_line.split(",")) # , is separator...
    N = np.array(M)

More pythonic way:

with open('Graph2021.txt', 'r') as the_file:
    N = np.array([each_line.split(",") for each_line in the_file]) # , is separator...
  
MSH
  • 1,743
  • 2
  • 14
  • 22
  • 1
    Hi, thanks for the help! It works but it seems that the answer from @Suneesh Jacob is slightly better as I am able to check if there is any NaN values using np.isnan(matrix).any() as he converted it to float – chloebutter Oct 22 '21 at 09:43
  • I would strongly recommend you to use context manager (the `with` part). But yes @ Suneesh Jacob gave a good answer. – MSH Oct 22 '21 at 10:17
-1
import numpy as np

N_lines = open('Graph2021.txt', 'r').readlines()
N_matrixlist = [list(map(float,i.strip().split(','))) for i in N_lines]
N = np.array(N_matrixlist)
Suneesh Jacob
  • 806
  • 1
  • 7
  • 15