0
import pandas as pd

s = pd.DataFrame([['b',40], ['cd',2], ['sf',20], ['sdf',30]],
                 columns=['a','score'])

This is the dataframe I have.I want to rank the dataframe according to the score in decreading order and then sort them accordingly.

I tried using df.rank with groupby but it didnt work.

expected output-

    a   score   Rank
0   b   40      1.0
1   sdf 30      2.0
2   sf  20      3.0
3   cd   2      4.0
ubuntu_noob
  • 2,305
  • 6
  • 23
  • 64
  • 1
    `s.sort_values('score', ascending=False).reset_index(drop=True)`, `s['Rank'] = s.index+1` – AChampion Jun 03 '18 at 19:30
  • @AChampion this doesnt work when I run it....are s.sort_values('score', ascending=False).reset_index(drop=True) and s['Rank'] = s.index+1 separate lines? – ubuntu_noob Jun 03 '18 at 19:51
  • `a = (s.sort_values('score', ascending= False))` and for Rank Column, use this `a['Rank'] = range(1, len(a)+ 1) ` – user96564 Jun 03 '18 at 20:00

0 Answers0