以下是我的数据框的外观。Expected_Output
列是我想要的/目标列。
Group Value Expected_Output
0 1 2 1
1 1 3 1
2 1 6 1
3 1 11 0
4 1 7 0
5 2 3 1
6 2 13 1
7 2 14 0
对于给Group
定的行,对于给定的行,我正在研究接下来的5行,并检查是否有行Value > 10
。如果为true,则我想在Expected_Output
其他0中返回1 。
例如,在中Group 1
,从第一行开始,aValue
的11(大于10)出现在3行之内,并且落在满足条件的“下5行窗口”之内,因此在中返回1 Expected_Output
。类似地,从第6行开始Group 2
,aValue
的14(大于10)出现在1行之内,并且落在满足条件的“下5行窗口”之内,因此in中返回1 Expected_Output
。
我df.groupby('Group')['Value'].rolling(-5).max() > 10
无济于事。
pd.Series.rolling
默认情况下向后看。若要向前看,可以反转数据框,然后反转GroupBy
结果。您需要添加一个,shift
因为您正在寻找下一个5个值。
def roller(x):
return x.rolling(window=5, min_periods=1)['Value'].max().shift().gt(10).astype(int)
df['Result'] = df.iloc[::-1].groupby('Group', sort=False).apply(roller).iloc[::-1].values
print(df)
Group Value Result
0 1 2 1
1 1 3 1
2 1 6 1
3 1 11 0
4 1 7 0
5 2 3 1
6 2 13 1
7 2 14 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句