Rank value from a column from lowest to highest

Question:

I want to to something like this

Input

   Animal Weight
0   Cat   1.2
1   Cat   1.1
2   Cat   2.5
3   Cat   0.8
4   Dog   5.3
5   Dog   4.7
6   Dog   4.2
7   Dog   3.6
8   Dog   4.9
9   Dog   6.0

Output

   Animal Weight Position
0   Cat   1.2       2
1   Cat   1.1       3
2   Cat   2.5       1
3   Cat   0.8       4
4   Dog   5.3       2
5   Dog   4.7       4
6   Dog   4.2       5
7   Dog   3.6       6
8   Dog   4.9       3
9   Dog   6.0       1

Is there any pandas way to do it ?

PS: If you have any proposition to change the title i take it ! 😉

Asked By: cormor

||

Answers:

You can use groupby.rank with method='dense', ascending=False:

df['Position'] = (df.groupby('Animal').rank(method='dense', ascending=False)
                    .astype(int) # optional
                  )

Output:

  Animal  Weight  Position
0    Cat     1.2         2
1    Cat     1.1         3
2    Cat     2.5         1
3    Cat     0.8         4
4    Dog     5.3         2
5    Dog     4.7         4
6    Dog     4.2         5
7    Dog     3.6         6
8    Dog     4.9         3
9    Dog     6.0         1
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.