如何在 pandas / Numpy中同时实现具有不重叠和滚动功能的功能? [英] How to implement a function with non overlapping and rolling features simultaneously in Pandas/Numpy?

查看:147
本文介绍了如何在 pandas / Numpy中同时实现具有不重叠和滚动功能的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在下一个窗口开头的函数重新启动的窗口上执行累积返回计算。我们来看一个例子:

I need to perform a cumulative return calculation over a window where the function restarts at the beginning of the next window. Let's look at an example:

A = pd.DataFrame([100, 101, 102, 103, 104, 105, 106, 107, 108],
                 columns=['A'], index=[range(1,10)])

假设我需要窗口的累积返回值,您将窗口大小定义为3,所需的输出将为

Say you define your window size to be 3, given that I need the cumulative returns of the window, the desired output would be

A['B'] = function(A['A'], window=3)

      A         B
1   100         0
2   101  0.010000
3   102  0.020000
4   103         0
5   104  0.009709
6   105  0.019417
7   106         0
8   107  0.009434
9   108  0.018868

谢谢。

推荐答案

IIUC,您可以使用 groupby 执行此操作:

IIUC, you can do this with a groupby:

>>> w = 3
>>> A["B"] = A.groupby(np.arange(len(A))//w)["A"].apply(lambda x: x/x.iloc[0]-1)
>>> A
     A         B
1  100  0.000000
2  101  0.010000
3  102  0.020000
4  103  0.000000
5  104  0.009709
6  105  0.019417
7  106  0.000000
8  107  0.009434
9  108  0.018868

这篇关于如何在 pandas / Numpy中同时实现具有不重叠和滚动功能的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆