I am trying to find consecutive values of zero and stuck with this problem for a couple of hours.
I have a DataFrame like:
Day | ID | Values
-------------------
1 | aa | 0
1 | aa | 0
1 | aa | 0
1 | aa | 0
1 | aa | 2.5
1 | aa | 2.3
1 | aa | 0
1 | aa | 0
1 | aa | 0
2 | aa | 0
2 | aa | 0
2 | aa | 2.3
2 | aa | 0
1 | bb | 0
1 | bb | 0
1 | bb | 0
1 | bb | 0
1 | bb | 3.5
I want to find consecutive values of zeros like this:
Day | ID | Values | consec_zeros
--------------------------------------
1 | aa | 0 | 0
1 | aa | 0 | 1
1 | aa | 0 | 2
1 | aa | 0 | 3
1 | aa | 2.5 | 4 # --> there were 4 of consecutive 0s
1 | aa | 2.3 | 0 # 2.5 just destroy consecutive values
1 | aa | 0 | 0
1 | aa | 0 | 1
1 | aa | 0 | 2
2 | aa | 0 | 0 # no 0s before this of Day 2
2 | aa | 0 | 1
2 | aa | 2.3 | 2
2 | aa | 0 | 0
1 | bb | 0 | 0 # --> no 0s before this in ID 'bb'
1 | bb | 0 | 1
1 | bb | 0 | 2
1 | bb | 0 | 3
1 | bb | 3.5 | 4
What I had attempted to do was:
g = df['Values'].ne(df['Values'].shift(1)).cumsum()
counts = df.groupby(['ID','Day',g])['Values'].transform('size')
df['consec_zeros'] = np.where(df['Values'].eq(0), counts, 0)
Since I'm new to this, please help and point me what I had done wrong.
Thank you in advance