Marcus Marcus - 3 months ago 23
Python Question

Converting dat file into array

I am having a dat file which contains data of the form:

0.23548 0.34938 0.54311 0.20902 0.52414 0.323418 1

for each observation and separated by each line. How would one convert this into an array with the first 6 variables as X's and the last variable as Y?

Thank you again!

Answer

The question is a bit unclear, but I'll try to answer anyway.

If the input file has the following structure (without the 1st and 3rd line):

X1      X2      X3      X4      X5      X6       Y(1-6)
0.23548 0.34938 0.54311 0.20902 0.52414 0.323418 1
X7      X8      X9      X10     X11     X12      Y(7-12)
0.23548 0.34938 0.54311 0.20902 0.52414 0.323418 1

then the following code should work. It returns a list of tuples (Xn,Yn).

points = []
for line in open("file.dat", "r").readlines():
    fields = map(float, line.split())
    xs, y = fields[:-1], fields[-1]
    for x in xs:
        points.append( (x,y) )

print points