GroupBy.cumcount()

pandas.core.groupby.GroupBy.cumcount

GroupBy.cumcount(ascending=True)

Number each item in each group from 0 to the length of that group - 1.

Essentially this is equivalent to

>>> self.apply(lambda x: Series(np.arange(len(x)), x.index))
Parameters:

ascending : bool, default True

If False, number in reverse, from length of group - 1 to 0.