![](/img/trans.png)
[英]Pandas rolling_max with variable window size specified in a df column
[英]Create rolling windows in pandas based on window size specified in another column
我有一個 pandas dataframe 我想滾動求和,其中 window 由另一列指定。
例如,
values_to_sum | 窗口大小 | 滾動總和 |
---|---|---|
1 | 6 | 17 |
2 | 5 | 16 |
1 | 2 | 4 |
3 | 5 | 19 |
4 | 5 | 鈉 |
6 | 4 | 鈉 |
2 | 3 | 鈉 |
4 | 3 | 鈉 |
嘗試在滾動 function 中調用列window_size
會導致錯誤ValueError: window must be an integer
。
對於滾動 function,如何逐行調用列window_size
?
使用列表理解:
df["rolling_sum"] = [np.nan
if j + ws > len(df.index)
else df.values_to_sum.iloc[j: j+ws].sum()
for j, ws in enumerate(df.window_size)]
如果當前索引( j
)加上np.nan
大小( ws
)超過數據幀的長度( len(df.index)
),則放置 np.nan ; 否則用 iloc 得到iloc
並sum
。
要得到
values_to_sum window_size rolling_sum
0 1 6 17.0
1 2 5 16.0
2 1 2 4.0
3 3 5 19.0
4 4 5 NaN
5 6 4 NaN
6 2 3 NaN
7 4 3 NaN
注意:您可以預先定義df_length = len(df.index)
並使用它來避免在理解中重復尋找它的長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.