0

Here is df, I want to Rank on value on group "Id" , ranking within class

df['Rank']=df.groupby(["Id"])[' value'].rank(ascending=0)

Sample df

Expected Result

Expected Result

Result what I get from above code Result what I get from above code

Above code works well if value are unique Example df

Example df

Result

  • Your example is ambiguous. Can you `print(df.sample(5).to_dict("list"))` and add it to your post with the matching expected output ? – Timeless Dec 02 '22 at 06:26

1 Answers1

0

IIUC, use a dense method on pandas.Series.rank with pandas.Series.astype :

df['Rank']= df.groupby('ID')['Value'].rank(ascending=False, method='dense').astype(int)

# Output :

print(df)

   ID Class  Value  Rank
0  US     A     10     1
1  US     B     10     1
2  US     C      2     2
3  US     D      2     2

Input used :

   ID Class  Value
0  US     A     10
1  US     B     10
2  US     C      2
3  US     D      2
Timeless
  • 22,580
  • 4
  • 12
  • 30