1

For the following example data frame, I'm working at grouby class and descendingly ranking the score.

 stu_id class name score 0 1 A Jack 45 1 2 A Oscar 75 2 3 B Emile 60 3 4 B Sophie 64 4 5 B Jim 85 5 6 A Thomas 55 6 7 A David 60 7 8 B Lee 60 8 9 B Elvis 70 9 10 A Frank 75 10 11 A James 90 

I have tried:

df['rank'] = df.groupby(['class'])['score'].rank(ascending=True) df 

Result:

 stu_id class name score rank 0 1 A Jack 45 1.0 1 2 A Oscar 75 4.5 2 3 B Emile 60 1.5 3 4 B Sophie 64 3.0 4 5 B Jim 85 5.0 5 6 A Thomas 55 2.0 6 7 A David 60 3.0 7 8 B Lee 60 1.5 8 9 B Elvis 70 4.0 9 10 A Frank 75 4.5 10 11 A James 90 6.0 

But my expected output should like this, why my code doesn't work out? Thanks.

 stu_id class name score rank 0 1 A Jack 45 1 1 2 A Oscar 75 4 2 3 B Emile 60 1 3 4 B Sophie 64 2 4 5 B Jim 85 4 5 6 A Thomas 55 2 6 7 A David 60 3 7 8 B Lee 60 1 8 9 B Elvis 70 3 9 10 A Frank 75 4 10 11 A James 90 5 

1 Answer 1

1

method='dense'

The default ranking uses average to resolve ties. In group A, Oscar and Frank share the same score, which is related to ranks 4 and 5. Under 'average' logic, both get set to 4.5: (4+5)/2, and the next value is ranked 6 so long as there are no ties with it, which is the case for James. With 'dense', the ties are given the lower rank (4 in this case) then the next distinct value continues the ranking at 5.

df['rank'] = df.groupby(['class'])['score'].rank(method='dense').astype(int) stu_id class name score rank 0 1 A Jack 45 1 1 2 A Oscar 75 4 2 3 B Emile 60 1 3 4 B Sophie 64 2 4 5 B Jim 85 4 5 6 A Thomas 55 2 6 7 A David 60 3 7 8 B Lee 60 1 8 9 B Elvis 70 3 9 10 A Frank 75 4 10 11 A James 90 5 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.