简体   繁体   中英

Calculate average of every 7 instances in a dataframe column

I have this pandas dataframe with daily asset prices: Picture of head of Dataframe

I would like to create a pandas series (It could also be an additional column in the dataframe or some other datastructure) with the weakly average asset prices. This means I need to calculate the average on every 7 consecutive instances in the column and save it into a series.

Picture of how result should look like

As I am a complete newbie to python (and programming in general, for that matter), I really have no idea how to start.

I am very grateful for every tipp!

I believe need GroupBy.transform by modulo of numpy array create by numpy.arange for general solution also working with all indexes (eg with DatetimeIndex ):

np.random.seed(2018)

rng = pd.date_range('2018-04-19', periods=20)
df = pd.DataFrame({'Date': rng[::-1], 
                   'ClosingPrice': np.random.randint(4, size=20)})  
#print (df)

df['weekly'] = df['ClosingPrice'].groupby(np.arange(len(df)) // 7).transform('mean')
print (df)
    ClosingPrice       Date    weekly
0              2 2018-05-08  1.142857
1              2 2018-05-07  1.142857
2              2 2018-05-06  1.142857
3              1 2018-05-05  1.142857
4              1 2018-05-04  1.142857
5              0 2018-05-03  1.142857
6              0 2018-05-02  1.142857
7              2 2018-05-01  2.285714
8              1 2018-04-30  2.285714
9              1 2018-04-29  2.285714
10             3 2018-04-28  2.285714
11             3 2018-04-27  2.285714
12             3 2018-04-26  2.285714
13             3 2018-04-25  2.285714
14             1 2018-04-24  1.666667
15             0 2018-04-23  1.666667
16             3 2018-04-22  1.666667
17             2 2018-04-21  1.666667
18             2 2018-04-20  1.666667
19             2 2018-04-19  1.666667

Detail :

print (np.arange(len(df)) // 7)
[0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM