开发者

how to get to various attributes in the same order in python

I have a file of lines and this in turn saves information, speed, timing and type of surfaces for each line. I w开发者_如何学运维ant 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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜