I have a pandas dataframe as below:
df = pd.DataFrame({'X':[1,1,1, 0, 0]})
df
X
0 1
1 1
2 1
3 0
4 0
Now I want to create another variable 'Y' and Values for Y should be based on the below condition:
If X = 1 , Y=1
If X = 0 and previous X = 1, Y = 2
If X = 0 and previous x = 0, Y = 0
So, my final output should look like below:
X Y
0 1 1
1 1 1
2 1 1
3 0 2
4 0 0
This can be achieved by iterating over rows and setting up a current and previous row and using iloc but I want a more efficient way of doing this faster