Function for monthly media calculation

Asked

Viewed 204 times

-2

I want to calculate the temperature average of each month of the year using a function. It’s not working. Follow the code I tried

import pandas as pd

tabela = pd.read_csv('DadosClimaticos2018Londrina.csv', sep =';')
tabela['Mes'] = pd.DatetimeIndex(tabela['Data'], yearfirst = True).month
tabela.to_csv('novo.csv',sep = ';', index = False)
    
def mediatemp(soma):
    soma = 0
    quant = 0
    for i in range(len(tabela)):
        linha= tabela.iloc[i]
        temp = linha['Temperatura']
        soma = soma + temp
        quant = quant + 1
        media = temp/quant
    return media

print(mediatemp)
  • 1
  • Not knowing how the data is in your spreadsheet is difficult. But you have tried using the df.mean()? It is a native function of Pandas to calculate the average

  • Another thing: You seem to be dividing the gross column of temperature by the amount of days. You need to sum up the temperature column first.

1 answer

0

Assuming the code of obtaining the data is correct, the average function should be something like this

def mediatemp(tabela):
    soma = 0
    for i in range(len(tabela)):
        linha= tabela.iloc[i]
        temp = linha['Temperatura']
        soma += temp
    return soma / (i+1)

I think you should review the concepts of object-oriented language. I didn’t get the point soma requested by the function. The same function is called without () nor arguments. Finally, its variable soma was not being used in the calculation of the media, that in the code you presented would only return the value you calculated in the last cycle.

Despite the code I presented, there are many other solutions for this purpose, many of them probably even better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.