1
$\begingroup$

I have the following data frame:

enter image description here

I would like to add a column with value equal to 1 if flag is 0 and incrementally add 1 in the following rows until the next 0 is encountered (as given in the example below).

enter image description here

I have been able to generate the sequence, but the code is extremely slow, so is there a faster way to generate the sequence?

$\endgroup$
1
  • 1
    $\begingroup$ Can you show us your attempt? $\endgroup$ – ukemi Feb 24 '19 at 9:25
0
$\begingroup$

I don't know how you have tested it the first time, here is my logic. It supposes the first element in flag is 0!

df = pd.DataFrame({'memberid': [1]*11,
                   'flag': [0,0,1,1,0,1,0,0,0,1,1],
                   })
df['seq'] = ""
for i in range(0, len(df)):
    df.loc[i, 'seq'] = 1 if df.loc[i, 'flag'] == 0 else  df.loc[i - 1, 'seq'] + 1
print(df)

Another solution using lambda:

df = pd.DataFrame({'memberid': [1] * 11,
                   'flag': [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1]
                   })

def f(flag):
    global previous_seq
    previous_seq = 1 if flag == 0 else previous_seq + 1
    return previous_seq

previous_seq = 0
df['seq'] = df[['flag']].apply(lambda x: f(*x), axis=1)
print(df)

I am not sure if it is faster than the first solution....

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.