Python 如何在数据帧中应用带有窗口参数的自定义函数?
我必须对数据帧执行以下操作:Python 如何在数据帧中应用带有窗口参数的自定义函数?,python,pandas,numpy,Python,Pandas,Numpy,我必须对数据帧执行以下操作: a 1.0 1.5 1.3 1.2 1.9 0.8 然后我想将我的新自定义函数应用到这个列,它有一个窗口参数,我的意思是,它只需要从起点处理n个项目: def hislack(x, window): # I only want to work with the last n items x = x[:-window,] # and do some stuff (this is a nosense example, just a simple s
a
1.0
1.5
1.3
1.2
1.9
0.8
然后我想将我的新自定义函数应用到这个列,它有一个窗口参数,我的意思是,它只需要从起点处理n个项目:
def hislack(x, window):
# I only want to work with the last n items
x = x[:-window,]
# and do some stuff (this is a nosense example, just a simple sum)
r = np.sum(x)
return r
因此,为了将此函数应用到名为b
的新列中,我使用了以下方法:
df['b'] = hislack(df['a'].values, 3)
但它返回以下内容:
a b
1.0 3.9
1.5 3.9
1.3 3.9
1.2 3.9
1.9 3.9
0.8 3.9
这只是最后一行的结果:0.8+1.9+1.2=3.9
因此,预期产出为:
a b
1.0 Nan
1.5 Nan
1.3 3.8
1.2 4.0
1.9 4.4
0.8 3.9
如何防止对所有行应用相同的公式结果?您需要:
或:
一般来说,您可以执行以下操作:df['a'].rolling(window).apply(fun)
将窗口的参数传递给rolling
,并将函数传递给apply
df['a'].rolling(3).sum() # here 3 is the window parameter for your function and sum
# is the function/operation you want to apply to each window
#0 NaN
#1 NaN
#2 3.8
#3 4.0
#4 4.4
#5 3.9
#Name: a, dtype: float64
df['a'].rolling(3).apply(sum)