Pandas:使用3个周期的窗口进行计算

2024-03-28 13:15:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何计算下一个关系。公式是这样的:它需要最后三个 行,然后使用该数据计算公式。使用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)

公式: enter image description here

Formula

我所尝试的:

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


Tags: 数据df关系sqrtresultnanwindow公式
1条回答
网友
1楼 · 发布于 2024-03-28 13:15:47
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

相关问题 更多 >