Home > Enterprise >  Increment the value in a new column based on a condition using an existing column
Increment the value in a new column based on a condition using an existing column

Time:10-12

I have a pandas dataframe with two columns:

temp_1  flag
1       0
1       0
1       0
2       0
3       0
4       0
4       1
4       0
5       0
6       0
6       1
6       0

and I wanted to create a new column named "final" based on : if "flag" has a value = 1 , then it increments "temp_1" by 1 and following values as well. If we find value = 1 again in flag column then the previous value in "final" with get incremented by 1 , please refer to expected output I have tired using .cumsum() with filters but not getting the desired result.

Expected output

temp_1  flag    final
1      0       1
1      0       1
1      0       1
2      0       2
3      0       3
4      0       4
4      1       5
4      0       5
5      0       6
6      0       7
6      1       8
6      0       8

CodePudding user response:

Just do cumsum for flag:

>>> df['final'] = df['temp_1']   df['flag'].cumsum()
>>> df
    temp_1  flag  final
0        1     0      1
1        1     0      1
2        1     0      1
3        2     0      2
4        3     0      3
5        4     0      4
6        4     1      5
7        4     0      5
8        5     0      6
9        6     0      7
10       6     1      8
11       6     0      8
>>> 
  • Related