【发布时间】:2014-03-02 09:20:24
【问题描述】:
使用:Windows 上的 Python 2.7.1
您好,我担心这个问题有一个非常简单的答案,但我似乎无法找到合适且有效的解决方案(我的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 列表范围的索引。我也知道在循环中修改列表的长度必须小心。可以肯定的是,我要么不够小心,要么完全忽略了一个更简单的解决方案。
在我试图帮助自己的谷歌搜索中,我遇到了 pandas(图书馆),但我觉得没有它我可以解决这个问题,(我更愿意这样做)。
非常感谢任何输入。非常感谢。
【问题讨论】:
-
您应该使用
dictionary而不是 2 个列表:weather_dict = {1:14.0,2:14.5,3:14.5,4: None, etc}。您可以使用所有任意值初始化dict,然后填写您拥有的数据。 -
谢谢你,试试看!
标签: python arrays python-2.7