试试这个:
df.groupby('ID')['Type'].agg(lambda x: (x=='In').rolling(3).apply(lambda x: x.all()).max())
Out[34]:
ID
1 0.0
2 1.0
Name: Type, dtype: float64
对符合条件的组返回 1,否则返回 0。
它首先按 ID 分组并采用 Type 列。对于您的示例,它有两个组:{1: ['In', 'In', 'Out', 'In'], 2: ['Out', 'In', 'In', 'In', 'Out']}。对于每个组 (x),它首先创建一个布尔系列 x=='In'。系列是[True, True, False, True] 和[False, True, True, True, False]。现在,在这些系列上,它应用了滚动功能。它一次需要三个并评估x.all()。对于第一组,前三个 ([True, True, False]) 和后三个 ([True, False, True]) 返回 False,因为这三个都应该是 True。这两个 False 的最大值为 0。对于第二组,滚动方法将产生 ([False, True, True], [True, True, True], [True, True, False]),因此对于第二组 x.all() 将是 True,因此最大值将为 1。
Series.rolling() 我相信是在 pandas 0.18 中引入的。对于早期版本,您可以使用:
df.groupby('ID')['Type'].agg(lambda x: pd.rolling_apply(x=='In', 3, lambda x: x.all()).max())