Pandas number rows within group in increasing order Pandas number rows within group in increasing order python-3.x python-3.x

Pandas number rows within group in increasing order


Use groupby/cumcount:

In [25]: df['C'] = df.groupby(['A','B']).cumcount()+1; dfOut[25]:    A  B  C0  A  a  11  A  a  22  A  b  13  B  a  14  B  a  25  B  a  3


Use groupby.rank function.Here the working example.

df = pd.DataFrame({'C1':['a', 'a', 'a', 'b', 'b'], 'C2': [1, 2, 3, 4, 5]})dfC1 C2a  1a  2a  3b  4b  5df["RANK"] = df.groupby("C1")["C2"].rank(method="first", ascending=True)dfC1 C2 RANKa  1  1a  2  2a  3  3b  4  1b  5  2