I am having trouble properly incrementing a counter variable within a for loop.
I have a variable called flag
, and I want to create a new variable called num
based on the values in flag
.
Input:
'flag'
FALSE
TRUE
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
Desired output:
'flag' 'num'
FALSE 1
TRUE 1
TRUE 1
TRUE 1
FALSE 2
TRUE 2
FALSE 3
TRUE 3
TRUE 3
The goal is to start the num counter at 1 and keep that counter at 1 until another False
instance occurs in the flag
column. This would be continued until the end of the df.
My code:
def num(z):
i = 0
for x in range (0,len(z)):
if z['flg'] == False:
return i + 1
else:
return i
df['num']=df.apply(num, axis=1)
I have tried incrementing the I counter in numerous places, but no luck...