Python 使用前面的4行增强每列
我有一个数据帧:Python 使用前面的4行增强每列,python,pandas,dataframe,data-munging,Python,Pandas,Dataframe,Data Munging,我有一个数据帧: df = Feat1 Feat2 Feat3 1 3 2 4 7 1 6 1 6 2 9 4 5 8 5 0 3 1 我想创建一个数据帧,这样对于每一行t>4,每一列都是t-1+0.75*t-2+0.5*t-3+0.25*t-4 因此,对于此df,我将有:
df = Feat1 Feat2 Feat3
1 3 2
4 7 1
6 1 6
2 9 4
5 8 5
0 3 1
我想创建一个数据帧,这样对于每一行t>4,每一列都是t-1+0.75*t-2+0.5*t-3+0.25*t-4
因此,对于此df,我将有:
df = Feat1 Feat2 Feat3
1 3 2
4 7 1
6 1 6
2 9 4
8.75 14 9.5
14.25 23 6.75
这样做的最佳方法是什么?递归计算不可矢量化,因为使用了改进性能:
最后一行的计数是多少?@jezrael更改了,8.75+0.75*2+0.5*6+0.25*4=14.25谢谢,答案已编辑。
from numba import jit
@jit(nopython=True)
def f(d):
for t in range(4, d.shape[0]):
d[t] = d[t-1] + 0.75*d[t-2] + 0.5*d[t-3] + 0.25*d[t-4]
return d
df = pd.DataFrame(f(df.to_numpy().astype(float)), index=df.index, columns=df.columns)
print (df)
Feat1 Feat2 Feat3
0 1.00 3.0 2.00
1 4.00 7.0 1.00
2 6.00 1.0 6.00
3 2.00 9.0 4.00
4 8.75 14.0 9.50
5 14.25 23.0 15.75