tags:

views:

102

answers:

2

hello everyone, I have a file of lines and this in turn saves information, speed, timing and type of surfaces for each line. I want to do is sort this information in a np.array in the order shown below where the id is the number of the line.

(id)   0   1   2   3   4   5   6   7   8   9

0   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10

1   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

2   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

3   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

4   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

5  t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

... thanks for any response

A: 

Maybe this will get you started...

data ='''
(id)   0   1   2   3   4   5   6   7   8   9

0   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10

1   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

2   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

3   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

4   t1 t2 t3 t4 t5 t6  t7 t8 t9 t10 

5  t1 t2 t3 t4 t5 t6  t7 t8 t9 t10'''

for line in data.strip().split('\n'):
    line = line.strip()
    if line:
        print '*'.join(line.split())

output:

(id)*0*1*2*3*4*5*6*7*8*9
0*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
1*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
2*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
3*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
4*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
5*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
telliott99
+2  A: 

Your may find numpy.loadtxt useful.

For example, suppose you have a file with these contents:

datafile:

(id)   0   1   
0   1 smooth 
1   11  choppy
2   20  turbulent
3   2  smooth
4   5  choppy
5  7   bumpy

Then you can load the data into a numpy structured array with

import numpy as np
arr=np.loadtxt('datafile',
               dtype=[('id','int'),('speed','float'),('surface','|S20')], 
               skiprows=1)

Notice you can skip the first line of the datafile by specifying skiprows=1.

Then you can access rows as usual with numeric indices, such as arr[1], and you can access columns by names, such as arr['speed'].

And you can get the speed in the 3rd row with arr[3]['speed'] or arr['speed'][3].

For more info on structured arrays, see http://docs.scipy.org/doc/numpy/user/basics.rec.html

unutbu
Thanks ~unutbu, this is great info.
telliott99