Home > Back-end >  Add count column to dataframe in 3 step intervals
Add count column to dataframe in 3 step intervals

Time:11-24

I'm looking for a quick solution to group by ColA and add a 'count' column in 3 step intervals. Example below:

Original DF:

ColA 
 G
 G
 G
 G
 G
 G
 G
 G
 G
 B
 B
 B
 B
 B
 B
 B
 B
 B

Need to Group by ColA and create 'ColB' which is basically an order column but in 3 step intervals. My real dataset I need the step to be 5, but for example sake I did 3.

Desired DF:

ColA     ColB
 G        1
 G        1
 G        1
 G        2
 G        2
 G        2
 G        3
 G        3
 G        3
 B        1  
 B        1
 B        1
 B        2 
 B        2 
 B        2
 B        3
 B        3
 B        3

thanks

CodePudding user response:

I would groupby ColA and get the integer division of the cumcount by the number of steps needed 1:

df['ColB'] = df.groupby('ColA').cumcount()//3 1

output:

   ColA  ColB
0     G     1
1     G     1
2     G     1
3     G     2
4     G     2
5     G     2
6     G     3
7     G     3
8     G     3
9     B     1
10    B     1
11    B     1
12    B     2
13    B     2
14    B     2
15    B     3
16    B     3
17    B     3
  • Related