简体   繁体   English

如何从文本文件读取数组数据到numpy数组?

[英]How to read array data into numpy array from text file?

I have a text file, data.txt , having data in this format: 我有一个文本文件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]]

How can I read data in this format into numpy array in jupyter ? 如何在jupyter中将这种格式的数据读入numpy数组?

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

This should work and is generalizable to other types than float : 这应该可以工作并且可以泛化为除float之外的其他类型:

with open("data.txt") as infile:
    np.fromstring( infile.read().replace("[","").replace("]", ""), sep="   ").reshape(-1,3)

Note: np.fromstring returns a 1d array, I added a reshaping assuming 3 columns. 注意: np.fromstring返回一个1d数组,我假设3列添加了重塑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM