简体   繁体   中英

How to read array data into numpy array from text file?

I have a text file, data.txt , having data in this format:

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

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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