Python 检查Pandas中GroupBy内的负滚动窗口中的条件
下面是我的数据帧的外观<代码>预期输出列是我的预期/目标列Python 检查Pandas中GroupBy内的负滚动窗口中的条件,python,pandas,numpy,pandas-groupby,Python,Pandas,Numpy,Pandas Groupby,下面是我的数据帧的外观预期输出列是我的预期/目标列 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
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
对于给定的组
,从给定的行开始,我查看下一行5行,并检查是否有值>10
。如果为true,则我希望在预期的\u输出中返回1,否则返回0
例如,在组1
中,从第一行开始,11的值(大于10)出现在3行内,并落在满足条件的“下5行窗口”内,因此在预期输出中返回1。与组2中的第6行类似,14的值(大于10)出现在1行内,并落在满足条件的“下5行窗口”内,因此在预期输出中返回1
我尝试了df.groupby('Group')['Value'].rolling(-5).max()>10
但没有效果。您可以尝试对数据帧进行分组,并使用数据帧索引来获取下一个可能的5个值,并检查是否有任何大于10的值
df['Expected_Output'] =df.groupby(['Group'])['Value'].transform(lambda y:list(map(lambda x: 1 if any(y.loc[set(np.arange(x+1,x+6)).intersection(y.index)] >10) else 0,y.index)))
输出:
默认情况下会向后看。要向前看,可以反转数据帧,然后反转GroupBy
结果。您需要包含一个,因为您正在查找接下来的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
您应该尝试对Pandas对象使用Pandas/NumPy方法任何
/设置
/三元语句以将布尔转换为整数;所有这些都很好,但当矢量化解决方案可用时,这些都不是最优的。谢谢@jpp的建议,我将合并它:-)
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