2014-02-05 70 views
1

使用:Python的2.7.1在Windows填充缺失值

你好,我擔心這個問題,有一個非常簡單的答案,但我似乎無法找到一個適當和有效的解決方案(我有有限的python經驗)。我正在編寫一個應用程序,從第三方API(wundergorund)下載歷史氣象數據。事情是,有時在給定的時間內沒有價值(例如,我們在凌晨5點有20度,上午6點沒有值,上午7點有21度)。我需要在任何給定的小時內確切地獲得一個溫度值,所以我想我可以適合我所擁有的數據並評估我失蹤的點(使用SciPy的polyfit)。這很酷,但是,我在處理程序時遇到問題以檢測列表是否缺少小時,如果是,插入缺少的小時並計算溫度值。我希望是有道理的..

我在處理的時間和溫度列表嘗試如下:

from scipy import polyfit 

# Evaluate simple cuadratic function 
def tempcal (array,x): 

    return array[0]*x**2 + array[1]*x + array[2] 


# Sample data, note it has missing hours. 
# My final hrs list should look like range(25), with matching temperatures at every point 
hrs = [1,2,3,6,9,11,13,14,15,18,19,20] 
temps = [14.0,14.5,14.5,15.4,17.8,21.3,23.5,24.5,25.5,23.4,21.3,19.8] 

# Fit coefficients 
coefs = polyfit(hrs,temps,2) 

# Cycle control 
i = 0 
done = False 

while not done: 

    # It has missing hour, insert it and calculate a temperature 
    if hrs[i] != i: 

     hrs.insert(i,i) 
     temps.insert(i,tempcal(coefs,i)) 

    # We are done, leave now 
    if i == 24: 

     done = True 

    i += 1 

我明白爲什麼這不工作,該方案最終將試圖訪問索引超出hrs列表的範圍。我也知道修改循環內的列表長度必須小心。當然,我要麼不夠小心,要麼完全忽視更簡單的解決方案。

在我的搜索幫助中,我碰到了熊貓(圖書館),但我覺得我可以在沒有它的情況下解決這個問題(我寧願這麼做)。

任何輸入,非常感謝。非常感謝。

+1

您應該使用'dictionary'而不是2個列表:'weather_dict = {1:14.0,2:14.5,3:14.5,4:None等}'。您可以使用所有的任意值初始化「dict」,然後填寫您擁有的數據。 – IanAuld

+0

謝謝你,會給它一個機會! – cilop

回答

0

當我等於21.它意味着列表中的第二十二個值。但只有21個值。

在未來,我建議您使用帶斷點的PyCharm進行調試。或try-except建設。

0

不知道我會推薦這種內插值的方式。我會使用圍繞缺失值的最近點而不是整個數據集。但是使用numpy你建議的方式非常簡單。

hrs = np.array(hrs) 
temps = np.array(temps) 

newTemps = np.empty((25)) 
newTemps.fill(-300) #just fill it with some invalid data, temperatures don't go this low so it should be safe. 

#fill in original values 
newTemps[hrs - 1] = temps 
#Get indicies of missing values 
missing = np.nonzero(newTemps == -300)[0] 

#Calculate and insert missing values. 
newTemps[missing] = tempcal(coefs, missing + 1) 
+0

我不知道這樣的索引是可能的,但肯定是有幫助的。另外我不會使用numpy,但我肯定會嘗試一下。非常感謝 ! (沒有足夠的代表upvote你的答案大聲笑) – cilop