1

I have a dataframe with incremental float values

   Number
0 0.679484 
1 0.079027 
2 0.003132 
3 0.092761 
4 0.055500 
5 0.055500 
6 0.055500 
7 0.003132 

i need to add a new column assigning number between 1 -5 based on existing column on the basis of their values in ascending order.

1 Answer 1

2

You can use Series.rank with method 'dense' which assigns rank from minimum to maximum incrementing by 1 between groups

df['rank'] = df['Number'].rank(method = 'dense').astype(int)


    Number      rank
0   0.679484    5
1   0.079027    3
2   0.003132    1
3   0.092761    4
4   0.055500    2
5   0.055500    2
6   0.055500    2
7   0.003132    1
Sign up to request clarification or add additional context in comments.

4 Comments

thanks... one thing how does dense stop at 5 .. my entire dataframe has more than 1000 rows but i need to limit the ranking till only 50.
Rank does not have a limit parameter so you cannot control the number. What you can do is filter the data after assigning rank. df[df['Rank'] <= 50] will only show rows where rank is less than or equal to 50
Second option is to sort the data first and apply rank to first 50 rows
thanks Vaishali... I have come across "pd.qcut" which seems to work fine... with my issue..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.