在我的领域中,很多数据文件的格式是这样的:
1.0 0.4 -0.3 0.2 1.0
2.2 -0.3 3.2 2.2 1.2
0.5 0.3 0.3 -4.4 1.2
0.2 1.2 -0.6
其中表示的数据序列只是一个一维数组(它们被任意分组为每行5列,最后一行除外)。
我可以用下面的hack读到这篇文章
txtdata = open('data.dat').read().replace('\n', ' ')
data = np.fromstring(txtdata, sep=' ')
但肯定有更好的方法吧?不需要对数据迭代两次?loadtxt
和genfromtxt
似乎不支持这种方式。
发布于 2015-08-12 16:20:41
假设你没有多余的空格:
with open('file') as f:
array = []
for line in f:
array.append([float(x) for x in line.split()])
您可以将循环压缩为嵌套的列表理解:
with open('file') as f:
array = [[float(x) for x in line.split()] for line in f]
https://stackoverflow.com/questions/31970301
复制相似问题