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

标签 python python-3.x pandas

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

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/

相关文章:

python - virtualenv 之间莫名其妙的 Urllib2 问题。

python-3.x - 如何在 mac Os 中将 openCv 与 Python3 链接起来

python - Pandas :对同一列中的情侣进行分组

python - 使用相似的列合并 2 个数据框

python - 如何从 regex.findall 的匹配中返回字典列表?

python - Pandas 被最后一个分隔符分割

python - 如何在忽略 NaN 值的同时将我的 DataFrame 转换为字典?

python - 如何使自定义状态discord.py

python - 无法同时抓取字符串和列表

python - 如何在Python中比较两个不同DataFrame的单元格值?