Crusader
Crusader

Reputation: 333

How to count values between 2 specific values in dataframe

Lets say there is a dataframe like below :

enter image description here

I would like to count the number of "xyz" between each "abc" in the column label and have that information into another column. The output would look like below :

enter image description here

How can we achieve this using python/pandas?

Upvotes: 0

Views: 44

Answers (1)

Harvey
Harvey

Reputation: 304

import pandas as pd
df = pd.DataFrame({"label":['abc','xyz','xyz','abc','abc','xyz','xyz','xyz','xyz','abc']})

sign = 'abc'
counter = 0
result = []
flag = 0
for idx, row in df.iterrows():
    if row['label'] == sign and flag==0:
        flag=1
    elif row['label']==sign and flag==1:
        result.extend([counter] + [0] * (counter+1))
        counter = 0
        flag = 0
    else:
        counter+=1
        
df['count'] = result

Upvotes: 1

Related Questions