Importing data and variable names from a text file in Python -
i have text file containing simulation data (60 columns, 100k rows):
a b c 1 11 111 2 22 222 3 33 333 4 44 444
... in first row variable names, , beneath (in columns) corresponding data (float type).
i need use these variables data in python further calculations. example, when insert:
print(b)
i need receive values second column.
i know how import data:
data=np.genfromtxt("1.txt", unpack=true, skiprows = 1)
assign variables "manually":
a,b,c=np.genfromtxt("1.txt", unpack=true, skiprows = 1)
but i'm having trouble getting variable names:
reader = csv.reader(open("1.txt", "rt")) row in reader: list.append(row) variables=(list[0])
how can change code variable names first row , assign them imported arrays ?
instead of trying assign names, might think using associative array, known in python dict
, store variables , values. code (borrowing liberally csv
docs):
import csv open('1.txt', 'rt') f: reader = csv.reader(f, delimiter=' ', skipinitialspace=true) linedata = list() cols = next(reader) print(cols) col in cols: # create list in linedata each column of data. linedata.append(list()) line in reader: in xrange(0, len(linedata)): # copy data line correct columns. linedata[i].append(line[i]) data = dict() in xrange(0, len(cols)): # create each key in dict data in column. data[cols[i]] = linedata[i] print(data)
data
contains each of variables, can accessed via data['varname']
.
so, example, data['a']
list ['1', '2', '3', '4']
given input provided in question.
i think trying create names based on data in document might rather awkward way this, compared dict-based method shown above. if want that, though, might reflection in python (a subject don't know about).
Comments
Post a Comment