【问题标题】:Find moving average of the smallest n values in m sized window在 m 大小的窗口中查找最小 n 值的移动平均值
【发布时间】:2020-03-29 17:22:12
【问题描述】:

我有这样的个人股票价值数据:

UserId Stock Value    Time
1        APL  20  '2019-01-01'
1        MCR  40  '2019-01-01'
1        ADX  60  '2019-01-01'
3        AGL  10  '2019-01-01'
...

我必须按用户分组,对于每只股票 x,我必须找到该用户在股票 x 之前的 20 支最新股票中 10 支最有价值股票的平均值。因此,我首先按 userId 分组,然后遍历每个股票 x,执行以下操作:选择股票 x 之前用户最近的 20 只股票,进一步从该窗口中选择 10 只最有价值的股票,取平均值并将其添加到股票 x 的新列。之后我的数据集将如下所示:

UserId Stock Value    Time    MovingAverage
1        APL  20  '2019-01-01'     20
1        MCR  40  '2019-01-01'     30
1        ADX  60  '2019-01-01'     40
3        AGL  10  '2019-01-01'     10
...

到目前为止,我一直在尝试在Python中使用rolling如下:

df = df.sort_values(['userId','time'], ascending=['true','false']) 
df['roll'] = df.groupby('userId')['Value'].transform(lambda x: x.rolling(20,1).mean())

我不知道如何获取窗口中 10 个最高值的平均值!我不反对使用滚动以外的其他技术,这似乎是最流行的方法。

另一个问题是一些股票的数量少于 20 只,但我认为使用 rolling(20,1) 可以缓解这个问题。但是,如果少于 10 只股票,例如 8 只股票,我只需要获取最后 8 只股票的平均值。

【问题讨论】:

  • 我认为这有点接近正确的方向。
    希望得到任何反馈!
    newcol = df.groupby('userId')['value'].rolling(20,1).apply(lambda x: np.partition(x,10).mean())df['roll'] = newcol.reset_index(level=0, drop=True)

标签: python pandas window-functions rolling-computation


【解决方案1】:

想通了。发布以防其他人处于类似情况。我定义了自己的函数,然后简单地使用了 rolling.apply()。最终变得相当简单。

首先,我定义了将执行上述帖子中描述的行为的函数。

def gm(arr):
    if (arr.size > 10):
        x = np.partition(arr, 9).mean()
    else:
        x = arr.mean()
    return x

然后,rolling.apply() 发挥了它的魔力:

newcol = df.groupby('userId')['value'].rolling(20,1).apply(lambda x: gm(x), raw=True)
df['roll'] = newcol.reset_index(level=0, drop=True)

我仍然不确定最后的索引,但结果似乎是我想要的。

【讨论】:

    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多