Incremental Counter flag for a matching condition on subsequent time series data

asi*_*imo 6 python pandas

I have a dataframe that looks like below

ID      DATE          PROFIT
2342  2017-03-01       457
2342  2017-06-01       658
2342  2017-09-01       3456
2342  2017-12-01       345
2342  2018-03-01       235
2342  2018-06-01       23
808   2016-12-01       200        
808   2017-03-01       9346
808   2017-06-01       54
808   2017-09-01       314
808   2017-12-01       57
....
....
Run Code Online (Sandbox Code Playgroud)

For each ID:

I want to find out if the Profit has stayed between 200 and 1000. I want to do it in such a way that a counter( a new column) indicates how many quarters (latest and previous) in succession have satisfied this condition. If for some reason, one of the intermediate quarters does not match the condition, the counter should reset.

So the output should look something like :

ID      DATE          PROFIT    COUNTER
2342  2017-03-01       457        1
2342  2017-06-01       658        2
2342  2017-09-01       3456       0
2342  2017-12-01       345        1
2342  2018-03-01       235        2
2342  2018-06-01       23         0
808   2016-12-01       200        1
808   2017-03-01       9346       0
808   2017-06-01       54         0
808   2017-09-01       314        1
808   2017-12-01       57         0
....
....
Run Code Online (Sandbox Code Playgroud)

I am thinking of using the shift functionality to access/condition on the previous rows, however if there is a better way to check if condition in datetime values, it will be good to know.

小智 -1

像下面这样简单的事情难道不起作用吗?

if profit_value>200 and profit_value<1000:
   cntr+=1
else:
   cntr=0
Run Code Online (Sandbox Code Playgroud)