Sequence number groupby ID with reset
<p>I'am looking for a way to gÃ©nÃ©rate a sequence of numbers that reset on every break</p>

<p>Example </p>

<pre><code>ID  VAR
A   0
A   0
A   1
A   1
A   0
A   0
A   1
A   1
B   1
B   1
B   1
B   0
B   0
B   0
B   0
</code></pre>

<p>Each time var is at 1 and ID the same as before, you start the counter.
but if ID is not the same or VAR is 0 you start again from 0</p>

<p>Desired output </p>

<pre><code>ID  VAR DESIRED
A   0   0
A   0   0
A   1   1
A   1   2
A   0   0
A   0   0
A   1   1
A   1   2
B   1   1
B   1   2
B   1   3
B   0   0
B   0   0
B   0   0
B   0   0
</code></pre>

<p>You can create an intermediate index, and then <code>groupby</code> this index and <code>ID</code>, cumsumming up on <code>VAR</code>:</p>

<pre><code>df['ix'] = df['VAR'].diff().fillna(0).abs().cumsum()

df['DESIRED'] = df.groupby(['ID','ix'])['VAR'].cumsum()

In [21]: df
Out[21]:
   ID  VAR  ix  DESIRED
0   A    0   0        0
1   A    0   0        0
2   A    1   1        1
3   A    1   1        2
4   A    0   2        0
5   A    0   2        0
6   A    1   3        1
7   A    1   3        2
8   B    1   3        1
9   B    1   3        2
10  B    1   3        3
11  B    0   4        0
12  B    0   4        0
13  B    0   4        0
14  B    0   4        0
</code></pre>

python pandas