Jade Bell
Jade Bell

Reputation: 41

How to calculate moving average for temperature?

This is the output I need:

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

This is my code:

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()

My code currently prints out up until the year 1957 and it prints out the wrong averages for each year. What do I need to fix?

Upvotes: 0

Views: 233

Answers (2)

Hamza
Hamza

Reputation: 6025

Using pandas would be most sane way to go:

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

Upvotes: 1

Chanran Kim
Chanran Kim

Reputation: 449

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))

I coded in the direction of modifying your code as little as possible. One thing to note is your file need to be longer than window size.

Upvotes: 2

Related Questions