2015-02-24 143 views
0

所以我想平均每600行。我得到一個超出範圍的Python錯誤索引,並且數字沒有正確顯示。幫幫我?Python錯誤代碼

import numpy as np 

data = np.loadtxt('Y:/Canopy/PSUone.txt', delimiter = ',', skiprows = 0) 
shape = np.shape(data) 
data_you_want = data[:,3] 
daily_averages = list() 

for i,d in enumerate(data_you_want): 
    if (i % 600) == 0: 
     avg_for_day = np.mean(data_you_want[i - 600:i]) 
     daily_averages.append(avg_for_day) 

with open('Y:/Canopy/newPSUone.txt', 'w') as f: 
    f.write('Wind U Direction\n') 
    f.write('------------------\n') 
    for i, d in enumerate(data_you_want): 
     s = '{0:4.3f}\n'. format(daily_averages[i]) 
     f.write(s) 

f.close() 
+1

你的輸入文件是怎麼樣的?更新到你的文章 – Hackaholic 2015-02-24 17:56:58

+0

'data_you_want = data [:,3]'給出錯誤> TypeError:列表索引必須是整數,而不是元組 – ForceBru 2015-02-24 17:58:23

+0

備註,當i是0時,i %0將是真實的,所以你將平均行-600:0,這可能不是你想要的。 – David 2015-02-24 17:58:34

回答

0

我認爲你正在運行到的問題是該位:

for i,d in enumerate(data_you_want): 
    if (i % 600) == 0: 
     avg_for_day = np.mean(data_you_want[i - 600:i]) 
     daily_averages.append(avg_for_day) 

...其次是這樣的:

for i, d in enumerate(data_you_want): 
    s = '{0:4.3f}\n'. format(daily_averages[i]) 
    f.write(s) 

因爲你只有走的每第600行從data_you_want到平均值爲daily_averages,您將有len(data_you_want) // 600元素在daily_averages。如果你迭代data_you_want並嘗試採取daily_average[i],那麼你將達到i大於daily_averages的長度,並且你會得到一個錯誤。