![](/img/trans.png)
[英]How to apply array function (previous row calculation) with pandas group by
[英]Pandas function calculation utilising previous row
具有一個“輸入”列的數據框。 我想添加另一個將輸入行乘以0.5 +(上一行Out值+ 1)的Out列。 我嘗試過輪班,但認為我缺少一些基本知識。
輸入數據框:
df
Out[11]:
Input
0 10
1 20
2 30
3 20
4 30
5 0
6 10
7 20
輸出數據幀:
df
Out[11]:
Input Out
0 10 5
1 20 16
2 30 32
3 20 43
4 30 59
5 0 60
6 10 66
7 20 77
df.assign(Out=df.Input.cumsum() / 2 + np.arange(len(df)))
Input Out
0 10 5.0
1 20 16.0
2 30 32.0
3 20 43.0
4 30 59.0
5 0 60.0
6 10 66.0
7 20 77.0
這是解決此問題的小技巧:
import pandas as pd
df = pd.DataFrame({'input':[10,20,30,20,30,0,10,20]})
print(df)
輸入數據框:
input
0 10
1 20
2 30
3 20
4 30
5 0
6 10
7 20
在這種情況下,您實際上正在執行的是累積總和的變體,我們可以按以下方式建模:
df['out'] = ((df['input']/2).cumsum()) + (df['input'].notnull()).cumsum().add(-1)
輸出結果:
input out
0 10 5.0
1 20 16.0
2 30 32.0
3 20 43.0
4 30 59.0
5 0 60.0
6 10 66.0
7 20 77.0
您將缺少第0
個索引的值,因為那里沒有先前的'Out'
值。
df['Input'] * 0.5 + (df['Out'].shift(1) + 1)
Out[24]:
0 NaN
1 16.0
2 32.0
3 43.0
4 59.0
5 60.0
6 66.0
7 77.0
dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.