Python 如何将数组数据从文本文件读入numpy数组?
我有一个文本文件,Python 如何将数组数据从文本文件读入numpy数组?,python,arrays,numpy,text-files,Python,Arrays,Numpy,Text Files,我有一个文本文件,data.txt,其中包含以下格式的数据: [[ 1.0 2.0 3.0] [1.0 2.0 3.0] [1.0 2.0 3.0] [1.0 2.0 3.0]] 如何将此格式的数据读入jupyter中的numpy数组?这应该可以工作,并且可以推广到float以外的其他类型: import numpy as np with open("data.txt") as infile: my_array = np.array([map
data.txt
,其中包含以下格式的数据:
[[ 1.0 2.0 3.0]
[1.0 2.0 3.0]
[1.0 2.0 3.0]
[1.0 2.0 3.0]]
如何将此格式的数据读入
jupyter
中的numpy
数组?这应该可以工作,并且可以推广到float
以外的其他类型:
import numpy as np
with open("data.txt") as infile:
my_array = np.array([map(float,line.strip(" []\n").split()) for line in infile.readlines()])
with open("data.txt") as infile:
np.fromstring( infile.read().replace("[","").replace("]", ""), sep=" ").reshape(-1,3)
注意:
np.fromstring
返回一个1d数组,我添加了一个重塑,假设有3列。当我编写print(我的数组)时会出现此错误:[]您可能想花更多时间学习python。输出是一个列表。使用print(list(my_array))
@AmitGupta我修复了一个小错误,它现在应该可以工作了。错误回溯(最近一次调用最后一次)在()2 3中以infle:--->4 np.genfromtxt(infle.read().replace(“[”,”).replace(“]”,“]”,“]))5 6 OS错误:1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0未找到。@Amit确实我的代码包含一个bug,我对它进行了更新,现在它使用fromstring
而不是genfromtxt
。