'pandas DataFrame column manipulation using previous row value

I have below pandas DataFrame

color direction Total
-1.0 1.0 NaN
1.0 1.0 0
1.0 1.0 0
1.0 1.0 0
-1.0 1.0 NaN
1.0 -1.0 NaN
1.0 1.0 0
1.0 1.0 0

I am trying to update the total column based on below logic.

if df['color'] == 1.0 and df['direction'] == 1.0 then Total should be Total of previous row + 1. if Total of previous row is NaN, then 0+1

Note: I was trying to read the previous row total using df['Total'].shift() + 1 but it didnt work.

Expected DataFrame.

color direction Total
-1.0 1.0 NaN
1.0 1.0 1
1.0 1.0 2
1.0 1.0 3
-1.0 1.0 NaN
1.0 -1.0 NaN
1.0 1.0 1
1.0 1.0 2


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source