Reputation: 333
Lets say there is a dataframe like below :
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 :
How can we achieve this using python/pandas?
Upvotes: 0
Views: 44
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