xiaotong xu
xiaotong xu

Reputation: 311

Python dataframe rank series

What I have is a dataframe with over 2 columns like this

columnA columnB
    1      a
    1      b
    1      c
    2      d

I just want to rank columnA like this

columnA columnB rankA
    1      a      1
    1      b      2
    1      c      3
    2      d      1

So what should I do?

Upvotes: 3

Views: 101

Answers (1)

jezrael
jezrael

Reputation: 862681

Use groupby + cumcount:

df['rankA'] = df.groupby('columnA').cumcount() + 1
print (df)
   columnA columnB  rankA
0        1       a      1
1        1       b      2
2        1       c      3
3        2       d      1

Upvotes: 1

Related Questions