首页 > 解决方案 > Pandas:使用 3 个周期的窗口进行计算

问题描述

我想知道如何计算下一个关系。该公式执行此操作:它采用最后三行,然后使用该数据计算公式。并使用 3 的滚动窗口执行此操作

A   B   Formula Result
2   3     nan
3   4     nan
2   3    sqrt(3*0.33)
1   2    sqrt(3*0.33)
3   1    sqrt(6*0,33)
1   2    sqrt(6*0,33)

公式: 在此处输入图像描述

公式

我试过的:

df["Formula Result"] = sum((df["A"]-Df["B"])^2).rolling_window(3)

标签: pythonpandas

解决方案


df["Formula Result"] = (df.A
                          .rolling(3)
                          .apply(lambda x: np.sqrt(0.33) * np.linalg.norm(x - df.loc[x.index, "B"])))

滚动,然后在滚动窗口的索引上A达到相应的值。B该公式对应于两个向量之间的欧几里得距离,因此我们可以使用差的范数。方括号内乘以 0.33 等价于sqrt(0.33)从外乘。

你也可以不写np.linalg.norm

df["Formula Result"] = (df.A
                          .rolling(3)
                          .apply(lambda x: np.sqrt(sum(0.33 * (x - df.loc[x.index, "B"])**2))))

要得到

>>> df

   A  B  Formula Result
0  2  3             NaN
1  3  4             NaN
2  2  3        0.994987
3  1  2        0.994987
4  3  1        1.407125
5  1  2        1.407125

推荐阅读