将文件的行转换为numpy数组

时间:2018-02-16 05:55:48

标签: python numpy

我有一个文件,其中的数据是这样的

[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]

我只是想把它转换成numpy数组,就像这样

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

我尝试了以下代码:

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)

它只提供[]

2 个答案:

答案 0 :(得分:1)

在numpy中使用 array 方法。

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

<强>输出:

[[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'>

答案 1 :(得分:0)

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

如果你想要numpy数组:

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