簡體   English   中英

將自定義 function 應用於 pandas dataframe 依賴於可變數量的先前行

[英]Apply custom function to pandas dataframe which relies on variable number of previous rows

我想要一個有效的解決方案來向我的表中添加一列,該列計算該行的值與最后 N 行中的值之間的絕對差之和。 例如

數字 new_col_2 new_col_3 new_col_4
10 - - -
11 - - -
12 3 - -
9 5 6 -
8 5 8 10
12 7 7 8
new_col_2 => refers to calculating this for the last 2 rows. 
(12-10) + (12-11) => 3
(11-9) + (12-9) => 5

new_col_3 => refers to calculate this for the last 3 rows
(10-9) + (11-9) + (12-9) => 6
(11-8) + (12-8) + (9-8) => 8 

等等。

如果 N 是一個固定數字,我知道我可以使用以下方法輕松做到這一點:

df[new_col_N] = abs(df[number]-df[number].shift(N)) + abs(df[number]-df[number].shift(N-1)) + etc

但這假設 N 是固定的。我想寫一個 function ,我可以在其中添加這個帶有 N 的列作為可以更改的 integer 變量。

知道最有效的方法是什么嗎?

編輯:下面接受的答案會為我帶來以下解決方案:

df[new_col_name] = df['number'].rolling(window=period+1).apply(lambda x: np.sum(np.abs(x[:-1]-x[-1])))

我們可以做numpy廣播

n = 2 
a = df.number.values
df.loc[n:,'new'] = np.sum(np.abs(np.tril(np.triu(a-a[:,None],k=-n))),1)[n:]
df
Out[188]: 
   number new_col_2 new_col_3 new_col_4   new1
0      10         -         -         -    NaN
1      11         -         -         -    NaN
2      12         3         -         -    3.0
3       9         5         6         -    5.0
4       8         5         8        10    5.0
5      12         7         7         8    7.0

暫無
暫無

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

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