4

I want to assign a sequence number to each group of my samples. An example dataset:

product |  sales 
-----------------        
100     |  213    
100     |  4343
100     |  234
203     |  231
203     |  654
304     |  6765
404     |  534

My expected output:

product  |  sales   |  sequenced number     
-------------------------------------------
100      |    213   |       1
100      |   4343   |       2
100      |    234   |       3
203      |    231   |       1
203      |    654   |       2    
304      |   6765   |       1    
404      |    534   |       1

I tried to use this code:

df.groupby('product',as_index=False).apply(lambda x: x.loc[:,1]=(range(len(x))))

But got the error:

lambda cannot contain assignment

1 Answer 1

2

You want the cumulative count:

df['seq_no'] = df.groupby('product').cumcount() + 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.