For an assignment i need to read a file and write into a numpy array, the data consists of a sting and 2 floats:
# naam massa(kg) radius(km)
Venus 4.8685e24 6051.8
Aarde 5.9736e24 6378.1
Mars 6.4185e23 3396.2
Maan 7.349e22 1738.1
Saturnus 5.6846e26 60268
the following was my solution to this problem:
def dataread(filename):
temp = np.empty((1,3), dtype=np.object)
x = 0
f = open(filename,'r')
for line in f:
if line[0] !='#' :
l = line.split('\t')
temp[0,0], temp[0,1] , temp[0,2] = l[0] , float(l[1]) , float(l[2])
if x == 0:
data = temp
if x > 0:
data = np.vstack((data,temp))
x+=1
f.close()
return data
somehow this returns the following array:
[['Aarde' 5.9736e+24 6378.1]
['Aarde' 5.9736e+24 6378.1]
['Mars' 6.4185e+23 3396.2]
['Maan' 7.349e+22 1738.1]
['Saturnus' 5.6846e+26 60268.0]]
The first line is being read but does not end up in the array while the second row is read in twice. What am I doing wrong ? I'm new to python so any comments on efficiency are also very much appreciated
Thanks in advance
This will read in your three columns into a numpy structured array:
import numpy as np
data = np.genfromtxt(
'data.txt',
dtypes=None, # determine types automatically
names=['name', 'mass', 'radius'],
)
print(data['name'])
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.