【问题标题】:fill missing values in python array填充python数组中的缺失值
【发布时间】: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


【解决方案1】:

当 I 等于 21 时,表示列表中的第 20 秒值。但是只有 21 个值。

以后我建议您使用带有断点的PyCharm 进行调试。或try-except 建设。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我不知道这样的索引是可能的,但肯定是有帮助的。我也不怎么使用 numpy,但我肯定会尝试一下。非常感谢 ! (没有足够的代表来支持你的答案哈哈)
    猜你喜欢
    • 2016-08-26
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    相关资源
    最近更新 更多