1

I have data frame with repetition of IDs like

  slNo | Id
  -----|---
    0  | 1
    1  | 2
    2  | 2
    3  | 3
    4  | 3
    5  | 2

I would like to have a new column with the repetition count like this:

slNo | ID| count|
-----|-- |------|
0    | 1 | 1    |
1    | 2 | 1    |
2    | 2 | 2    |
3    | 3 | 1    |
4    | 3 | 2    |
5    | 2 | 3    |

can anybody please help?

sravand93
  • 25
  • 1
  • 4

2 Answers2

1

Try using cumcount with groupby:

df['count'] = df.groupby('Id').cumcount() + 1
print(df)

Output:

   slNo  Id  c
0     0   1  1
1     1   2  1
2     2   2  2
3     3   3  1
4     4   3  2
5     5   2  3
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Do this using Groupby.cumcount:

In [1616]: df['c'] = df.groupby('Id').cumcount()+1

In [1617]: df
Out[1617]: 
   slNo  Id  c
0     0   1  1
1     1   2  1
2     2   2  2
3     3   3  1
4     4   3  2
5     5   2  3
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58