【发布时间】:2020-01-15 16:00:52
【问题描述】:
我目前正在研究解决条件滚动平均值。 我创建了一个简化的数据集来演示: 在这个数据集中,我们有 3 家商店和 2 种产品,它们在 4 天内的销售量。
Picture of the dataset, Link to download the dataset
考虑到真实数据集包括数千家商店和数百种产品,我试图为同一数据帧内的商店/产品的每个组合实现滚动平均值计算。
通过使用下面的代码,我可以计算每行的滚动平均值,in the same manner other data scientist calculate a 10 days or 20 days moving average for a share price:
import pandas as pd
df = pd.read_csv (r'path\ConditionalRollingMean.csv')
df['Rolling_Mean'] = df.Quantity.rolling(2).mean()
甚至
df['Rolling_Mean'] = df.Quantity.rolling(window=2).mean()
这种方法的问题是计算是逐行完成的,与商店/产品组合无关。我正在寻找的是一个条件滚动平均值,它在遍历数据框时跟踪商店/产品组合,并逐行填充 df['Rolling_Mean'] 列。 (类似于this)
然后,此滚动平均值将用于滚动标准偏差计算,对此我只知道如何在整个数据帧中进行计算,而没有滚动方面。
df['mean']=df.groupby(['Quantity']).Qty.transform('mean')
df['std']=df.groupby(['Quantity']).Qty.transform('std')
将不同数据框中的商店/产品分开然后运行 df.Quantity.rolling(2).mean() 函数会更简单,但在我正在处理的情况下,这意味着创建超过 150 000 个数据帧。因此,为什么我要在 1 个数据帧内解决这个问题。
提前感谢您的帮助。
【问题讨论】:
标签: python pandas dataframe average rolling-computation