下面是这个示例 Dataframe ,我创建了一个函数来完成我想要的任务,计算Sales
滚动平均值(7,14天窗口),并将其移动到当前日期。如何仅计算特定日期2022-12-31
的**例如,我有很多行,我不想每次添加日期时都重新计算。
import numpy as np
import pandas as pd
ex = pd.DataFrame({'Date':pd.date_range('2022-10-01', '2022-12-31'),
'Store': np.random.choice(2, len(pd.date_range('2022-10-01', '2022-12-31'))),
'Sales': np.random.choice(10000, len(pd.date_range('2022-10-01', '2022-12-31')))})
ex.sort_values(['Store','Date'], ascending=False, inplace=True)
for days in [7, 14]:
ex['Sales_mean_' + str(days) + '_days'] = ex.groupby('Store')[['Sales']].apply(lambda x: x.shift(-1).rolling(days).mean().shift(-days+1))```
1条答案
按热度按时间nbysray51#
我重新定义了一个类似的 Dataframe ,因为使用随机变量生成器会使调试变得困难。在每次测试中, Dataframe 都会随机变化。
除了保持简单,我将使用2和3移动平均线时期。
它给出:
[Date, Store, Sales]
fmt_newRow
函数,该函数具有相应的子组g
fmt_newRow
以字典的形式返回一个新行,使用append
Pandas函数将其集成到 Dataframe 中per
-lastg
值用于计算新的行平均值