I want to go from this:
df
val1
0 0
1 0
2 32
3 0
to this:
df
val1 count
0 0 1
1 0 2
2 32 0
3 0 1
How do I count how many times 0 comes in a row?
CodePudding user response:
- Make groups
df.val1.ne(0).cumsum()
, this makes a new group every time val1 isn't 0. - Groupby those groups, and
cumsum()
where the number equals 0 in each group.
df['count'] = df.groupby(df.val1.ne(0).cumsum())['val1'].apply(lambda x: x.eq(0).cumsum())
print(df)
# Output:
val1 count
0 0 1
1 0 2
2 32 0
3 0 1
CodePudding user response:
You can use groupby.cumcount
using the non-0 values to restart the groups, then mask
:
m = df['val1'].ne(0)
df['count'] = df.groupby(m.cumsum()).cumcount().add(1).mask(m, 0)
Output:
val1 count
0 0 1
1 0 2
2 32 0
3 0 2