1

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

1 Answer 1

2

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
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

Legend. Thank you this is exactly what I was doing as well but I know it may sound stupid, I was not assigning it to a new variable. I reckon if you work on multiple projects at the same time, you are bound to do stupid mistakes, haha. FYI accepting the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.