This question already has an answer here:
How to increment a row count in groupby in DataFrame
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我需要在我的数据帧中订购计数器值为1、2、3等的重复项。输入数据帧如下所示:

         Key    Amount
         xyz     1000
         xyz1    870
         xyz2    1000
         xyz3    1000
         xyz4    650


和预期的输出为

         Key    Amount  Duplicate_order
         xyz     1000    1
         xyz1    870     1
         xyz2    1000    2
         xyz3    1000    3
         xyz4    650     1

最佳答案

使用cumcount

df['duplicate_order'] = df.groupby('Amount').cumcount()+1

    Key  Amount  duplicate_order
0   xyz    1000                1
1  xyz1     870                1
2  xyz2    1000                2
3  xyz3    1000                3
4  xyz4     650                1

关于python - 通过添加另一列来对我的 Pandas 数据框中的重复项进行排序[duplicate],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50748517/

10-11 22:05
查看更多