Harish reddy
Harish reddy

Reputation: 431

Increment values of a column based on the current row of another column and the previous row of the same column

I want to create a column with multiple conditions wherein if the column ' Batt' contains 'Discharge' and the previous row contains 'none' then increment the value by 1 starting with 0 if not then return the same value without any increments.

 Batt Disch            Continous Cycle count   
       None                0   
       None                0   
       Discharge           1  
       Discharge           1  
       None                1   
       Discharge           2  
       Discharge           2

Upvotes: 1

Views: 416

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71687

IIUC, You can create a boolean mask and then use Series.cumsum to get the result:

df['Continous Cycle count'] = (
    (df['Batt Disch'].eq('Discharge') &
     df['Batt Disch'].shift().eq('None'))
    .cumsum()
)

Result:

  Batt Disch  Continous Cycle count
0       None                      0
1       None                      0
2  Discharge                      1
3  Discharge                      1
4       None                      1
5  Discharge                      2
6  Discharge                      2

Upvotes: 1

Related Questions