如何将数字的多行文件读入1维numpy数组?

时间:2016-08-12 21:07:20

标签: numpy

我在文件中有一些数字

   8.89661443042575        17.8003874198066        17.8003323639473
   43.9969250561223        4.51593232168458        0.000000000000000E+000
   0.000000000000000E+000  0.000000000000000E+000

读取这些内容的最规范的方法是什么,结果是一维数字的numpy数组,8个元素长?

2 个答案:

答案 0 :(得分:1)

一种简单的方法是:

with open('data.txt', 'r') as f:
    a = np.array([float(field) for field in f.read().split()])

答案 1 :(得分:0)

不是最有效的代码(我假设),但它有效:

import numpy as np

a = []
with open('file.txt') as temp_file:
    for i in temp_file:
        a.append(i.split())  # removes whitespaces and split into one list per row
np_array = np.asarray([float(item) for sublist in a for item in sublist])  # flatten, str->float, create-array