python - 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)
解决方案
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
推荐阅读
- javascript - youtube 视频网址不适用于“video-react”npm 模块
- c# - 通过 lambda 创建实例
- hibernate - Spring Boot Data Jpa - @ManyToOne 加入 UUID id
- git - 暂时隐藏 Git 的特定更改
- javascript - 寻找js库推荐
- typescript - 如何在组件中使用 Angular 6 类装饰器?
- react-native - React-Native:如何在动画期间滚动时禁用 TouchableHighlight?
- javascript - 使用 jquery 在固定位置上可拖动和调整大小的 Div 元素
- angular - 如何将 http 请求响应映射到我在 TypeScript 中定义的对象
- android-graphview - 如何在 Android 的 GraphView 中更改 X 和 Y 轴数字的颜色?