I have a database of users with marks.
I want to loop into marks and get user positions. Let's say user1
marks are higher, the position would 1
and so on.
The output would be something like this:
user1 5121 1
user2 500 2
user3 400 3
I tried with:
sorted(range(len(user[marks])), key=lambda i: a[i], reverse=True)
But this only print out the highest to lowest.
My database model:
class user(db.Model):
id = db.Column(Integer, primary_key=True, autoincrement=True)
name = db.Column(String(250), nullable=False)
marks = db.Column(Integer, nullable=False)
position = db.Column(Integer, nullable=False)
CodePudding user response:
If you can get you data in Pandas DataFrame then you can do something like this:
import pandas as pd
df = pd.DataFrame({
"user": ['user1', 'user2', 'user3'],
"marks": [5121, 400, 500]
})
# Sort dataframe by marks, and use index as rank
df.sort_values(['marks'], ascending=False, ignore_index=True)
CodePudding user response:
I think you mean you want to find the rank. Try this:
import pandas as pd
df = pd.DataFrame({
"user": ['user1', 'user2', 'user3'],
"marks": [5121, 400, 500]
})
df['rank'] = df['marks'].rank(method='dense', ascending=False).astype(int)
df = df.sort_values('rank', ignore_index=True)
Your output would look like this:
user marks rank
0 user1 5121 1
1 user3 500 2
2 user2 400 3
ignore_index=True
would reindex based on rank as well
CodePudding user response:
You already achieved the sorted list of marks, highest to lowest, let's call it ranks
. Just enumerate it and add 1.
[(i 1,e) for i,e in enumerate(ranks)]
Not sure why pandas is needed. Provide exact fields and formats for more detail.