Home > front end >  Ranking data from highest to lowest
Ranking data from highest to lowest

Time:09-16

I want the program to get an input of 5 numbers which represent people. Then the program should rank the numbers from highest to lowest e.g(5=1, 1=5). I have been trying all day to figure out how to rank them but have no idea. New to programming, thank you very much.

number1 = []    
number2 = []    
number3 = []    
number4 = []
number5 = []

count = 0
    
while count < 1:
    a = int(input("enter score num 1"))
    number1.append(a)
    
    b = int(input("enter score num 2"))
    number2.append(b)
    
    c = int(input("enter score num 3"))
    number3.append(c)
    
    d = int(input("enter score num 4"))
    number4.append(d)
    
    e = int(input("enter score num 5"))
    number5.append(e)
        
    count  = 1
    
import pandas as pd    

df = pd.DataFrame(data={
    'names': ['d', 's', 'r', 'l', 'a'],
    'match1': [number1, number2, number3, number4, number5],
}) 

df["Rank"] = df["match1"].rank()
df["Rank"] = df["match1"].rank(method ='max')
df

code in question

CodePudding user response:

Assuming your dataframe is built correctly, you need to add ascending=False to your rank() method for the highest value to be rank 1:

df["rank"] = df["match1"].rank(ascending=False)

learn more with the method documentation here

EDIT: Data type issue. The data in match1 column are lists, which are 'object' datatypes in Pandas, which rank() cannot see/evaluate. Try this:

while count < 1:
    a = int(input("enter score num 1"))
    b = int(input("enter score num 2"))
    c = int(input("enter score num 3"))
    d = int(input("enter score num 4"))
    e = int(input("enter score num 5"))
    count  = 1

import pandas as pd

df = pd.DataFrame(
    data={
        "names": ["d", "s", "r", "l", "a"],
        "match1": [a, b, c, d, e],
    }
)

df["rank"] = df["match1"].rank(ascending=False)

CodePudding user response:

First of all, you need to prevent using the list to append your result. Instead, just directly assign the input to your variable like this.

count = 0

while count< 1:

    number1 = int(input("enter score num 1"))

    number2 = int(input("enter score num 2"))

    number3 = int(input("enter score num 3"))

    number4 = int(input("enter score num 4"))

    number5 = int(input("enter score num 5"))

    count  = 1

Secondly, if you are looking to rank the number and then sort it based on the rank, you can add another sort_values.

df

  names  match1
0     d      10
1     s      30
2     r      70
3     l      50
4     a      22

df["rank"] = df["match1"].rank(ascending=False)
df.sort_values('rank')

  names  match1  rank
2     r      70   1.0
3     l      50   2.0
1     s      30   3.0
4     a      22   4.0
0     d      10   5.0
  • Related