[英]Pandas: Find max in rolling window and return sum of another column for the row of the max and proceeding four rows
我有一個帶有兩列的 dataframe。 我想找到第一列的滾動 5 周期最大值,並計算滾動最大值行和前 4 行的值和第二列的總和。
下面是所需的 output 的示例,其中 Col1 和 Col2 如上所述,滾動最大值的第三列和所需計算結果的最后一列
這是設置前三列的代碼:
data ={'Col1': [4,2,3,4,5,6,5,4,3,2,1,4,3,2,1],
'Col2' :[10,20,10,15,10,20,10,15,10,20,10,15,10,20,10]}
df = pd.DataFrame(data)
df['Col1_Rolling5_Max'] = df['Col1'].rolling(5).max()
df
以下是所需 output 的示例:
您只能計算下一個Rolling5_Max
不同的行的滾動總和,然后向前填充以填充 rest。
import pandas as pd
import numpy as np
data ={'Col1': [4,2,3,4,5,6,5,4,3,2,1,4,3,2,1],
'Col2' :[10,20,10,15,10,20,10,15,10,20,10,15,10,20,10]}
df = pd.DataFrame(data)
df['Col1_Rolling5_Max'] = df['Col1'].rolling(5).max()
df['flag'] = df['Col1_Rolling5_Max'].ne(df['Col1_Rolling5_Max'].shift())
df['Sum_5_Col1_Before_Max']= np.where(df['flag']==True,df['Col2'].rolling(5).sum(),np.nan)
df.ffill(inplace=True)
df[['Col1','Col2','Col1_Rolling5_Max','Sum_5_Col1_Before_Max']]
Output
Col1 Col2 Col1_Rolling5_Max Sum_5_Col1_Before_Max
0 4 10 NaN NaN
1 2 20 NaN NaN
2 3 10 NaN NaN
3 4 15 NaN NaN
4 5 10 5.0 65.0
5 6 20 6.0 75.0
6 5 10 6.0 75.0
7 4 15 6.0 75.0
8 3 10 6.0 75.0
9 2 20 6.0 75.0
10 1 10 5.0 65.0
11 4 15 4.0 70.0
12 3 10 4.0 70.0
13 2 20 4.0 70.0
14 1 10 4.0 70.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.