填充python数组中缺少的值

填充python数组中缺少的值,python,arrays,python-2.7,Python,Arrays,Python 2.7,在Windows上使用:Python 2.7.1 您好,我担心这个问题的答案很简单,但我似乎找不到合适而有效的解决方案(我的python经验有限)。我正在编写一个应用程序,它只是从第三方API(wundergorund)下载历史天气数据。问题是,有时给定的一小时内没有温度值(例如,我们早上5点有20度,早上6点没有温度值,早上7点有21度)。我需要在任何一个给定的小时内有一个精确的温度值,所以我想我可以只拟合我的数据,并评估我缺少的点(使用SciPy的polyfit)。这很酷,但是,我在处理我的

在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列表范围的索引。我也知道在循环中修改列表的长度必须小心。当然,我不是不够仔细,就是完全忽略了一个更简单的解决方案

在我用谷歌搜索帮助自己的过程中,我遇到了熊猫(图书馆),但我觉得没有它我也能解决这个问题(我宁愿这样做)


非常感谢您的任何意见。非常感谢。

等我21岁的时候。它表示列表中的第二十二个值。但只有21个值


以后我建议您使用断点进行调试。或构造。

我不确定是否推荐这种插值方法。我会使用缺失值周围最近的点,而不是整个数据集。但是使用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)

您应该使用
字典
而不是两个列表:
天气预报={1:14.0,2:14.5,3:14.5,4:None等}
。您可以使用所有任意值初始化
dict
,然后填写您确实拥有的数据。谢谢,我们将试一试!我不知道这样的索引是可能的,但肯定是有帮助的。我也不怎么使用numpy,但我肯定会尝试一下。谢谢!(没有足够的代表投票支持你的答案lol)