簡體   English   中英

如何在pandas數據框中應用帶有window參數的自定義函數?

[英]How to apply a custom function with a window parameter in a pandas dataframe?

我必須遵循pandas數據幀:

a

1.0
1.5
1.3
1.2
1.9
0.8

然后我想將我的新自定義函數應用於此列,該列具有window參數,我的意思是,它只需要從起點處理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

如何防止對所有行應用相同的公式結果?

你需要DataFrame.rolling

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)

更一般地說,你可以這樣做: df['a'].rolling(window).apply(fun)你將window參數傳遞給rolling和要apply的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM