ggupta
ggupta

Reputation: 717

convert the lines of a file into numpy array

I have a files in which data is something like this

[1,2,3,4,5]
[4,2,3,4,5,6]
[3,12,3,34,5]
[3,4,5,6,7,8]
[2,3,4,5,6,6]
[2,3,4,5,5,4,3]
[1,2,3,23,2,1]

i just want to convert this into numpy array, something like this

[[1,2,3,4,5],[4,2,3,4,5,6]]

I tried following code:

import ast
import numpy as np
a = np.array([])
with open("test.txt","r") as f:
        for line in f:
                line = ast.literal_eval(line)
                np.append(line,a)

it is only giving []

Upvotes: 1

Views: 2561

Answers (2)

Rakesh
Rakesh

Reputation: 82795

Using array method in numpy.

import ast
from numpy import array

p = "PATH_TO_INPUT_FILE"
data = []
with open(p,"r") as f:
    for i in f.readlines():
        data.append(ast.literal_eval(i.strip()))
data = array(data)
print(data)
print(type(data))

Output:

[[1, 2, 3, 4, 5] [4, 2, 3, 4, 5, 6] [3, 12, 3, 34, 5] [3, 4, 5, 6, 7, 8]
 [2, 3, 4, 5, 6, 6] [2, 3, 4, 5, 5, 4, 3] [1, 2, 3, 23, 2, 1]]
<type 'numpy.ndarray'>

Upvotes: 1

Osman Mamun
Osman Mamun

Reputation: 2882

with open('file.txt') as f:
    data = []
    for line in f:
        words = line.replace('[', ''). replace(']', '').replace('\n', '').split(',')
        data.append([int(i) for i in words])

if you want numpy array:

with open('file.txt') as f:
    data = []
    for line in f:
        words = line.replace('[', ''). replace(']', '').replace('\n', '').split(',')
        data.append(np.array([int(i) for i in words]))

Upvotes: 0

Related Questions