Q:

Group based on a variable field, and then resetting the counter (cumcount) in python

I create a data frame
df = pd.DataFrame({"b": ['A','A','A','A','B', 'B','B','C','C','D','D', 'D','D','D','D','D','D','D','D','D'],"a": [-3,-4,2, -1, -3, -1,-7,-6, 1, 1, -1, 1,4,5,-3,2,3,4, -1, -2]})

check for negative values
df['val'] = df.a < 0

Add a cumulative count sum column, where the counter increases when previous values is not negative. (it means for every negative value the counter increases by 1 but if there are several -ve value, they are assumed to be single negative value and counter still increasing by 1)
df['val_1'] = (((df['val']) & (df['val'] != df['val'].shift())).cumsum()). the table is as below

    b  a    val  val_1
0   A -3   True      1
1   A -4   True      1
2   A  2  False      1
3   A -1   True      2
4   B -3   True      2
5   B -1   True      2
6   B -7   True      2
7   C -6   True      2
8   C  1  False      2
...

I want to restart the counting for a new value in the field 'b'. The counter should start from value 'B'. Any inputs in this regard will be helpful

A:

You can do this with groupby-transform:
df['val_2'] = df.groupby('b')['val'].transform(lambda x: ((x) & (x != x.shift())).cumsum())

Output:
    b   a   val     val_1
0   A   -3  True    1
1   A   -4  True    1
2   A   2   False   1
3   A   -1  True    2
4   B   -3  True    1
5   B   -1  True    1
6   B   -7  True    1
7   C   -6  True    1
8   C   1   False   1
9   D   1   False   0
10  D   -1  True    1
11  D   1   False   1
12  D   4   False   1
13  D   5   False   1
14  D   -3  True    2
15  D   2   False   2
16  D   3   False   2
17  D   4   False   2
18  D   -1  True    3
19  D   -2  True    3

Note that the first value counts as 1 if it is true, which might not be what you want - but it's taken from the code you supplied.

