Yufeng Yao
Yufeng Yao

Reputation: 53

How to assign a sequenced numbers to each value within same group? python

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

Upvotes: 4

Views: 138

Answers (1)

gmds
gmds

Reputation: 19885

You want the cumulative count:

df['seq_no'] = df.groupby('product').cumcount() + 1

Upvotes: 2

Related Questions