首页 > 解决方案 > 在 Python 中滚动使用以前的数据

问题描述

我想在 python 中执行以下操作

基本上我有一个如下表,y = 0.5

A | B | Result from column A
---
1   2   0.5
---
2   4   0.5*(0.5+ 2)
---
3   5   ...
---
4   4   ...
---

到目前为止,我有一个效率不高的循环,我想要一种矢量化的方法:

X = np.zeros((len(df),))
for i, (_, row) in enumerate(df.iterrows()):
    if i == 0:
        continue
    X[i] = y*(X[i - 1] +  row['A'])

你能帮我解决上述问题吗

谢谢

标签: pythonpandasapplyrolling-computation

解决方案


我的猜测是你应该使用 Pandas 滚动方法加入 lambda 表达式,类似于以下内容:

X = [your_Pandas_Serie]
rolling_window = X.rolling([the_length_of_your_Serie])

rolling_window.apply(lambda x: [your_function])

使用像 mean() 这样的简单滚动方法来熟悉并在实现最终解决方案之前使用 lambda 表达式。

我在交易软件中使用了相同的流程。


推荐阅读