Dávid Kókai
Dávid Kókai

Reputation: 67

How to take average in a timeframe python?

I am beginner in Python so I kindly ask your help. I would like to have a document where I have the first column as 2011.01 and the second column is the number of ARD 'events' in that month and the third column is the average of all of the ARD displayed in that month. If not, that e.g. 2012.07 0 0

I've already tried for 3 hours and now I am getting nervous.

I really much appreciate your help

import pandas as pd
from numpy import mean
from numpy import std
from numpy import cov
from matplotlib import pyplot
from scipy.stats import pearsonr
from scipy.stats import spearmanr
data = pd.read_csv('ARD.txt',delimiter= "\t")

month = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
day = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
year = ['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021']

ertek = data[:1].iloc[0].values
print(ertek)
print(data.head)

def list_to_string ( y, m, d):
    str = ""
    s = [y, m, d]
    str.join(s)
    return str

for x in year:
for y in month:
    for i in day:
        x = 1
        ertek = data[:x].iloc[0].values
        list_to_string(x, y, i)
        if ertek[0] == list_to_string[x, y, i]:
            print("")
            x += 1
        else:
            print("")

Result:

['2011.01.05.' 0.583333333]
<bound method NDFrame.head of              Date       ARB
0     2011.01.05.  0.583333
1     2011.01.06.  0.583333
2     2011.01.07.  0.590909
3     2011.01.09.  0.625000
4     2011.01.10.  0.142857
...           ...       ...
1284  2020.12.31.  0.900000
1285  2020.12.31.  0.900000
1286  2020.12.31.  0.900000
1287  2020.12.31.  0.900000
1288  2020.12.31.  0.900000

[1289 rows x 2 columns]>
 Traceback (most recent call last):
  File "C:\Users\Kókai Dávid\Desktop\python,java\python\stock-trading-ml-master\venv\Scripts\orosz\oroszpred.py", line 29, in <module>
   list_to_string(x, y, i)
   File "C:\Users\Kókai Dávid\Desktop\python,java\python\stock-trading-ml-master\venv\Scripts\orosz\oroszpred.py", line 21, in list_to_string
    str.join(s)
  TypeError: sequence item 0: expected str instance, int found

 Process finished with exit code 1

Upvotes: 0

Views: 108

Answers (1)

Joshua Voskamp
Joshua Voskamp

Reputation: 2044

I'm not quite certain I'm tracking your intent with the list_to_string function; if it's for string date comparison, let's sidestep that entirely by

df.iloc[:,0] = pd.to_datetime(df.iloc[:,0]
df.set_index('Date')
df['Month Average'] = df.Date.resample('M').mean()

Upvotes: 1

Related Questions