gpt4 book ai didi

python - 如何为同一组中的每个值分配一个序列号? Python

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:48 27 4
gpt4 key购买 nike

我想为我的每组样本分配一个序列号。示例数据集:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com