2

When using groupby(), how can I create a DataFrame with a new column containing an increasing index of each group. For example, if I have

df=pd.DataFrame('a':[1,1,1,2,2,2])
df
   a  
0  1  
1  1  
2  1  
3  2  
4  2  
5  2  

How can I get a DataFrame where the index resets for each new group in the column. The association between a and index is not important...just need to have each case of a receive a unique index starting from 1.

   a    idx
0  1    1
1  1    2
2  1    3
3  2    1
4  2    2
5  2    3
ERIHPAS
  • 21
  • 2

1 Answers1

1

The answer in the comments :

df['idx'] = df.groupby('a').cumcount() + 1