2010-02-03 56 views
1

我有一個行文件,這又保存了每行的信息,速度,時間和表面類型。我想要做的就是按照下面顯示的順序在np.array中排序該信息,其中id是行號。如何在Python中以相同順序獲取各種屬性

(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 

... 感謝任何迴應

+1

這是輸入?什麼是預期產出? – telliott99 2010-02-03 18:31:20

+0

是輸入數據...謝謝telliott99 – ricardo 2010-02-03 18:33:20

+1

和...你期望輸出什麼? – telliott99 2010-02-03 19:02:04

回答

2

你可能會發現numpy.loadtxt有用。

例如,假設有這些內容的文件:

數據文件:

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

然後就可以將數據裝載到一個numpy的結構化陣列

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

通知你可以通過指定skiprows=1跳過數據文件的第一行。

然後,您可以像往常一樣使用數字索引訪問行,例如arr[1], ,並且可以按名稱訪問列,如arr['speed']

你可以在第三排獲得速度arr[3]['speed']arr['speed'][3]

有關結構陣列的詳細信息,請參閱 http://docs.scipy.org/doc/numpy/user/basics.rec.html

+0

謝謝〜unutbu,這是很好的信息。 – telliott99 2010-02-04 13:03:03

0

也許這將讓你開始...

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()) 

輸出:

(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 
相關問題