'How to Append results in loop to data frame by index
I have data that consists of 10 items. Each item has 12 locations with sales for over a year. I want to calculate the moving averages for each item location week and append my results to the main table
Data Sample:
wkly_sales =
ID STORE WEEK_NUM TOTAL_NET_UNITS
100001 1 1 4
100001 1 2 5
100001 1 3 6
100001 2 1 9.5
100001 2 2 6
100001 2 3 33
100002 1 1 1
100002 1 2 9
100002 1 3 9
100002 2 1 1
100002 2 2 1
100002 2 3 2
Here is my code attempt:
for item in wkly_sales['ID'].unique():
items = wkly_sales[wkly_sales['ID']==item]
for loc in items['STORE'].unique():
locs = items[items['STORE']==loc]
locs['QUANTITY_SMA1'] = locs.TOTAL_NET_UNITS.rolling(1,min_periods=1).mean().shift().fillna(0)
# locs['QUANTITY_SMA5'] = locs.TOTAL_NET_UNITS.rolling(5, min_periods=5, center=False).mean().fillna(0)
# items['QUANTITY_SMA1'] = locs['QUANTITY_SMA1']
for index, i in locs.iterrows():
wkly_sales.at[index, 'QUANTITY_SMA1'] = i['QUANTITY_SMA1']
# wkly_sales.at[index, 'QUANTITY_SMA5'] = i['QUANTITY_SMA5']
The problem is I am not able to append the calculated moving averages to the main data frame by the indexes
Expected result:
wkly_sales =
ID STORE WEEK_NUM TOTAL_NET_UNITS QUANTITY_SMA1
100001 1 1 4. 0
100001 1 2 5 4
100001 1 3 6 5
100001 2 1 9.5 6
100001 2 2 6 9.5
100001 2 3 33 6
100002 1 1 1 33
100002 1 2 9 1
100002 1 3 9 9
100002 2 1 1 9
100002 2 2 1 1
100002 2 3 2 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
