簡體   English   中英

如何計算溫度的移動平均值?

[英]How to calculate moving average for temperature?

這是我需要的輸出:

Temperature anomaly filename:SacramentoTemps.csv
Enter window size:60
1940,-0.2331
1941,-0.2169
1942,-0.2150
1943,-0.2228
1944,-0.2107
1945,-0.1796
1946,-0.1667
1947,-0.1582
1948,-0.1585
1949,-0.1492
1950,-0.1711
1951,-0.1688
1952,-0.1490
1953,-0.1556
1954,-0.1548
1955,-0.1580
1956,-0.1420
1957,-0.1101
1958,-0.1017

這是我的代碼:

filename = input("Temperature anomaly filename:")
infile = open(filename, "r")
k = int(input("Enter window size:"))
infile.readline()

temp_list = []


for line in infile:
   line = line.strip()
   year,temp = line.split(",")
   temp = float(temp)
   temp_list.append(temp)

    index = k
for index in range(index,len(temp_list)-1-index):
    year = 1880 + index
    ave = sum(temp_list[index:index+k]) / (2*index+1)
    print(str(year)+","+"{:.4f}".format(ave))
infile.close()

我的代碼目前打印到 1957 年,它打印出每年錯誤的平均值。 我需要修復什么?

filename = "SacramentoTemps.csv"
infile = open(filename, "r")
k = int(input("Enter window size:"))

temp_list = []
for line in infile:
    line = line.strip()
    year, temp = line.split(",")
    temp = float(temp)
    temp_list.append(temp)
infile.close()

moving_average = []
for i, temp in enumerate(temp_list):
    average = temp
    if len(temp_list) - i < k:
        break
    for j in range(k):
        average += temp_list[i+j]
    moving_average.append(average/k)
    
    print(str(year) + "," + "{:.4f}".format(average))

我編碼的方向是盡可能少地修改你的代碼。 需要注意的一件事是您的文件需要長於窗口大小。

使用熊貓將是最明智的方法:

import pandas as pd
filename = "SacramentoTemps.csv"
window  = 2
data = pd.read_csv(filename)
data.temperature.rolling(window = window).mean().fillna(data.temperature)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM