简体   繁体   中英

How to compute the average of n rows and paste the answer to next n rows of pandas column?

I have a weekly sales dataframe

Sales           weekNum 
83                    1 
139                   2 
207                   3 
278                   4 
274                   5 
291                   6 
319                   7 
305                   8 

I want to compute the average of first 4 weeks and paste it in the index of week 5 to 8

And I want my output dataset to look like below

Sales   weekNum   4-PreviousWeekAverage
83            1 
139           2 
207           3 
278           4 
274           5          176.75
291           6          176.75
319           7          176.75
305           8          176.75

Similarly I also want to compute the 8 week average and paste it in the index of 5 to 8

I tried

for i in [4, 8]:
    newColumnName1 = '%s-PreviousWeekAverage' % i
    df[newColumnName1] = np.nan


    for ix in df.index:
        if ix - i >= 0:

            df.loc[ix, newColumnName1] = np.mean(sampledf.loc[ix-i:ix-1,'Sales'])

However it returns me the moving average like below

Sales   weekNum 4-PreviousWeekAverage
83           1  
139          2  
207          3  
278          4  
274          5            176.75
291          6            224.5
319          7            262.5
305          8            290.5

I am having an issue in looping , no able to figure out the correct script. Hence will appreciate the help.

groupby on weekNum and transform by mean .

df.groupby((df.weekNum - 1) // 4).Sales.transform('mean').shift(4)

0       NaN
1       NaN
2       NaN
3       NaN
4    176.75
5    176.75
6    176.75
7    176.75
Name: Sales, dtype: float64

IIUC

df.at[4:,'4-PreviousWeekAverage']=df.Sales.iloc[:4].mean()
df
Out[344]: 
   Sales  weekNum  4-PreviousWeekAverage
0     83        1                    NaN
1    139        2                    NaN
2    207        3                    NaN
3    278        4                    NaN
4    274        5                 176.75
5    291        6                 176.75
6    319        7                 176.75
7    305        8                 176.75

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