Home > Back-end >  Python calculate increment rows till a condition
Python calculate increment rows till a condition

Time:05-14

How to obtain the below result.

Sample Data with Output

Time To default is the column which is to be calculated. We need to get the increment number as Time to default and this increment should be till Default column is 1.

Above shown is for a sample account and the same has to be applied for multiple account id.

CodePudding user response:

Use:

m = df['Default'].eq(1).groupby(df['acct_id']).transform(lambda x: x.shift(fill_value=False).cummax())

df.loc[~m, 'new'] = df[~m].groupby('acct_id').cumcount()
print (df)
  acct_id  Default  new
0  xxx123        0  0.0
1  xxx123        0  1.0
2  xxx123        1  2.0
3  xxx123        1  NaN
  • Related