## 通过取消计算累积计数内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (6)

• 条纹基于flag == true累积。
• 条纹在取消时重置取消== true。
• 条纹什么都不做，重复当前的连胜。

``````df = pd.DataFrame(
{
"cond1": [True, False, True, False, True, False, True],
"cond2": [False, False, False, True, False, False, False]
})

df['flag'] = np.where(df['cond1'], 1, 0)
df['cancel'] = np.where(df['cond2'], 1, 0)

# Combined
df['combined'] = df['flag'] - df['cancel']

# Cumsum only
df['cumsum'] = df['combined'].cumsum()

df['cumsum_cumcount'] = df.where(df['cond1']).groupby((df['cond2']).cumsum()).cumcount()

# Cumcount then cumsum
df['cumsum_cumcount_cumsum'] = df.where(df['cancel'] == False).groupby(df['flag'].cumsum()).cumcount().cumsum()
``````
``````
cond1   cond2   flag    cancel  c2  c3  c1
0   True    False    1         0    0   0   1
1   False   False    0         0    1   1   1
2   True    False    1         0    2   1   2
3   False   True     0         1    0   2   1
4   True    False    1         0    1   2   2
5   False   False    0         0    2   3   2
6   True    False    1         0    3   3   3
``````
``````
cond1   cond2   streak
0   True    False     1
1   False   False     1
2   True    False     2
3   False   True      0
4   True    False     1
5   False   False     1
6   True    False     2
7   True    False     3
8   False   False     3
9   True    False     4
10  False   True      0
11  False   False     0
12  True    False     1
``````

### 1 个回答

``````df.groupby(df.cond2.cumsum()).cond1.cumsum()
Out[155]:
0     1.0
1     1.0
2     2.0
3     0.0
4     1.0
5     1.0
6     2.0
7     3.0
8     3.0
9     4.0
10    0.0
11    0.0
12    1.0
Name: cond1, dtype: float64
``````