我想为我的每组样本分配一个序列号。示例数据集:
product | sales
-----------------
100 | 213
100 | 4343
100 | 234
203 | 231
203 | 654
304 | 6765
404 | 534
我的预期输出:
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
我尝试使用这段代码:
df.groupby('product',as_index=False).apply(lambda x: x.loc[:,1]=(range(len(x))))
但出现错误:
lambda cannot contain assignment
最佳答案
你想要累计计数:
df['seq_no'] = df.groupby('product').cumcount() + 1
关于python - 如何为同一组中的每个值分配一个序列号? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55565569/