0

I have a text file with each line that looks like this :

[204, -12, -1016, 1]
[208, -32, -976, 1]
[192, -24, -1008, 1]

I need to convert this into a Numpy array like this :

data = [[204, -12, -1016, 1], [208, -32, -976, 1], [192, -24, -1008, 1]]

such that calling data[0] will give [204, -12, -1016, 1] and calling data[0][1] will give -12

Is it possible to do it?

  • just read it on python list casting as int and cast to array with np.asarray() https://numpy.org/doc/stable/reference/generated/numpy.asarray.html – Luis Bote Mar 18 '21 at 08:00
  • You should *fix whatever is generating this file*, but for now, you can probaly just use `np.array(list(map(eval, open('file.txt')))` or something to that effect – juanpa.arrivillaga Mar 18 '21 at 08:09
  • A more readable version without the eval: ```import numpy as np l = [] with open("mine.txt") as file: for line in file: line = list(map(int, line.strip().replace("[", "").replace("]", "").split(", "))) l.append(line) print(np.array(l))``` – MunsMan Mar 18 '21 at 08:19

0 Answers0