[英]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
你想要累积计数 :
df['seq_no'] = df.groupby('product').cumcount() + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.