I have a dataframe:
JavaScript
x
9
1
id value
2
0 a w
3
1 a l
4
2 a l
5
3 a w
6
4 a w
7
5 a w
8
6 a l
9
when I do df.groupby("id").cumcount()
it returns:
JavaScript
1
8
1
0 0
2
1 1
3
2 2
4
3 3
5
4 4
6
5 5
7
6 6
8
I want to count only those ones that equal w in column value and it must be in dataframe form:
JavaScript
1
5
1
0 0
2
3 0
3
4 1
4
5 2
5
How to do that with cumcount function?
Advertisement
Answer
Use:
JavaScript
1
4
1
res = df.groupby((df["value"] != df["value"].shift()).cumsum()).cumcount()
2
res = res[df["value"].eq("w")]
3
print(res)
4
Output
JavaScript
1
6
1
0 0
2
3 0
3
4 1
4
5 2
5
dtype: int64
6
As an alternative:
JavaScript
1
5
1
s = (df["value"] != df["value"].shift()).cumsum()
2
res = s.groupby(s).cumcount()
3
res = res[df["value"].eq("w")]
4
print(res)
5