Calculate unique data jumps using Python

Viewed 64

I have a time series data frame df1 like this:

DateTime      Power[HP]  PowerJump   PowerStart
01/01/2018    0          0           0
01/02/2018    10         0           1
01/03/2018    99         1           0
01/04/2018    20         0           0
01/05/2018    60         0           0
01/06/2018    70         0           0
01/07/2018    15         0           0
01/08/2018    95         1           0
01/09/2018    0          0           0
01/10/2018    10         0           1
01/11/2018    0          0           0
01/12/2018    95         1           1

Power Jump tags cases where power increased at least 20HP to 90HP or more. Power Starts tags every case where engine started producing power.

Now I would like to count cycles where cycle is either power production start or power jump. When power start is followed by the power jump it is counted as one.

enter image description here

There are 4 cycles in total for this data sample.

This is the expected output:

DateTime      Power[HP]  PowerJump   PowerStart  Cycle
01/01/2018    0          0           0           0
01/02/2018    10         0           1           1
01/03/2018    99         1           0           0
01/04/2018    20         0           0           0
01/05/2018    60         0           0           0
01/06/2018    70         0           0           0
01/07/2018    15         0           0           0
01/08/2018    95         1           0           1
01/09/2018    0          0           0           0
01/10/2018    10         0           1           1
01/11/2018    0          0           0           0
01/12/2018    95         1           1           1
1 Answers

Ok, I think I figured it out. My code:

df1.loc[0,'Cycle']=0
j = True
    
for i in range (1, len(df1)):            
    if df1.loc[i,'Power[HP]']!=0 and df1.loc[i-1,'Power[HP]']==0:
        df1.loc[i,'Cycle'] = 1
        j = False
    else:                
        if j == True:
            if df1.loc[i,'Power[HP]']>=90 and (df1.loc[i,'Power[HP]']-df1.loc[i-1, 'Power[HP]']>=20):
                df1.loc[i,'Cycle'] = 1  
            else:
                df1.loc[i,'Cycle'] = 0
        else:
            df1.loc[i,'Cycle'] = 0
            if df1.loc[i,'Power[HP]']>df1.loc[i-1,'Power[HP]']:
                j = False
            else:
                j = True
Related