In [1]:
import numpy as np
import pandas as pd
In [23]:
inventory = pd.Series(["W1","W1","W1","W1","W2","W1"])
Flag = pd.Series([0,0,1,1,0,0])
df=pd.DataFrame([inventory,Flag]).T
df.columns=['Week','Flag']
df
Out[23]:
Week | Flag | |
---|---|---|
0 | W1 | 0 |
1 | W1 | 0 |
2 | W1 | 1 |
3 | W1 | 1 |
4 | W2 | 0 |
5 | W1 | 0 |
In [24]:
df['G']=df.groupby('Week').Flag.apply(lambda x :(x.diff().ne(0)&x==1)|x==1)
Cntr=df.groupby([df.Week,df.G.cumsum()]).G.apply(lambda x : (~x).cumsum())
df['Cntr']=Cntr
df
Out[24]:
Week | Flag | G | Cntr | |
---|---|---|---|---|
0 | W1 | 0 | False | 1 |
1 | W1 | 0 | False | 2 |
2 | W1 | 1 | True | 0 |
3 | W1 | 1 | True | 0 |
4 | W2 | 0 | False | 1 |
5 | W1 | 0 | False | 1 |