I have following pandas DataFrame and trying to create a new "Value_Diff" column where it calculates the difference between current "value" if lable=0 with the previous value where label=1. If label=1 it sets the "Value_Diff" equals to 0. This process needs to be repeated for each group and if first label in the group is equal to 0 it should leave the "Value_Diff" equal to 0 until it reaches first label=1 and then follow the same logic ( group C in this example)
I can write a for loop and if statement for each individual group to do this, however was wondering if there is a better way to do this with using groupby, lambda or any other function.
here is the input:
group Date Value label
A 2020-03-01 -117 1
A 2020-03-02 -121 0
A 2020-03-03 -122 0
A 2020-03-04 -122 1
B 2020-03-05 -118 1
B 2020-03-06 -122 0
B 2020-03-07 -124 0
B 2020-03-08 -126 0
B 2020-03-09 -126 1
C 2020-03-10 -130 0
C 2020-03-11 -140 0
C 2020-03-12 -150 1
C 2020-03-13 -160 0
Answer should look like this:
group Date Value label Value_Diff
A 2020-03-01 -117 1 0
A 2020-03-02 -121 0 4 (-117-(-121)=4)
A 2020-03-03 -122 0 1
A 2020-03-04 -122 1 0
B 2020-03-05 -118 1 0
B 2020-03-06 -122 0 4
B 2020-03-07 -124 0 2
B 2020-03-08 -126 0 2
B 2020-03-09 -126 1 0
C 2020-03-10 -130 0 0
C 2020-03-11 -140 0 0
C 2020-03-12 -150 1 0
C 2020-03-13 -160 0 10
Sorry my first output didn't actually reflect what I wanted, because @BENY provided the solution to this output I'll leave this here to help others with the same question. Here is how the actual output should look like.
group Date Value label Value_Diff
A 2020-03-01 -117 1 0
A 2020-03-02 -121 0 4 (-117-(-121)=4)
A 2020-03-03 -122 0 5 (-117-(-122)=5)
A 2020-03-04 -122 1 0
B 2020-03-05 -118 1 0
B 2020-03-06 -122 0 4 (-122-(-118)=4)
B 2020-03-07 -124 0 6 (-124-(-118)=6)
B 2020-03-08 -126 0 8 (-126-(-118)=8)
B 2020-03-09 -126 1 0
C 2020-03-10 -130 0 0
C 2020-03-11 -140 0 0
C 2020-03-12 -150 1 0
C 2020-03-13 -160 0 10 (-150-(-160)=10)