我正在尝试在 pandas 数据帧上应用具有 3 年窗口的滚动函数。
import pandas as pd
# Dummy data
df = pd.DataFrame({'Product': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'Year': [2015, 2016, 2017, 2018, 2015, 2016, 2017, 2018],
'IB': [2, 5, 8, 10, 7, 5, 10, 14],
'OB': [5, 8, 10, 12, 5, 10, 14, 20],
'Delta': [2, 2, 1, 3, -1, 3, 2, 4]})
# The function to be applied
def get_ln_rate(ib, ob, delta):
n_years = len(ib)
return sum(delta)*np.log(ob[-1]/ib[0]) / (n_years * (ob[-1] - ib[0]))
预期输出是
Product Year IB OB Delta Ln_Rate
0 A 2015 2 5 2
1 A 2016 5 8 2
2 A 2017 8 10 1 0.3353
3 A 2018 10 12 3 0.2501
4 B 2015 7 5 -1
5 B 2016 5 10 3
6 B 2017 10 14 2 0.1320
7 B 2018 14 20 4 0.2773
我努力了
df['Ln_Rate'] = df.groupby('Product').rolling(3).apply(lambda x: get_ln_rate(x['IB'], x['OB'], x['Delta']))
但这是行不通的。
我发现了好几个类似的帖子
将自定义滚动函数应用于数据框 https://stackoverflow.com/questions/45517686/applying-custom-rolling-function-to-dataframe- 这个没有明确的答案
熊猫滚动应用自定义 https://stackoverflow.com/questions/40954560/pandas-rolling-apply-custom- 这个没有多个参数
在滚动窗口上的 pandas 数据框上应用自定义函数 https://stackoverflow.com/questions/30806838/apply-custom-function-on-pandas-dataframe-on-a-rolling-window- 这个有rolling.apply
...但它不显示语法。
两者似乎都不对劲。任何指向正确语法的指示将不胜感激。