Add a sequence number to each element in a group using python

I stumbled upon the answer which was embarrassingly simple. The groupby statement has a ‘cumcount()’ option which will enumerate group items.

df['sequence']=df.groupby('patient').cumcount()

The caveat is that the records have to be in the order you want them enumerated.

Leave a Comment