Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Pandas/Numpy中同时实现具有非重叠和滚动特性的功能?_Python_Numpy_Pandas_Dataframe - Fatal编程技术网

Python 如何在Pandas/Numpy中同时实现具有非重叠和滚动特性的功能?

Python 如何在Pandas/Numpy中同时实现具有非重叠和滚动特性的功能?,python,numpy,pandas,dataframe,Python,Numpy,Pandas,Dataframe,我需要在函数在下一个窗口开始时重新启动的窗口上执行累积回报计算。让我们看一个例子: A = pd.DataFrame([100, 101, 102, 103, 104, 105, 106, 107, 108], columns=['A'], index=[range(1,10)]) 假设您将窗口大小定义为3,假设我需要窗口的累积回报,那么所需的输出将是 A['B'] = function(A['A'], window=3) A B

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

A = pd.DataFrame([100, 101, 102, 103, 104, 105, 106, 107, 108],
                 columns=['A'], index=[range(1,10)])
假设您将窗口大小定义为3,假设我需要窗口的累积回报,那么所需的输出将是

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,您可以使用
分组方式来执行此操作:

>>> 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