Hi all, i use this code to rank a list, the problem is if there is a tie break it gives inaccurate info, how can i fix this so tie breaks will be based on original list order.
list1 = {} for i, e in enumerate(change): list1[e] = i rank = 1 for key in sorted(list1.keys(), reverse=FALSE): # These lines rank a list from high to low but doesn't sort change[list1.get(key)] = rank rank = rank + 1 You'll maybe need to post a working example of your code, rather than a snippet that does not work 'as is', so that we don't have to try and 2nd guess what the missing parts are.
from tkinter import * a = [1, 2, 4, 3, 4, 5, 6, 7] test = [] list1 = {} for i, e in enumerate(a): list1[e] = i rank = 1 for key in sorted(list1.keys(), reverse=TRUE): a[list1.get(key)] = rank rank = rank + 1 test += [a] print(test) What i would like to happen is a rank from 1 to 8
(Mar-19-2023, 04:15 AM)klatlap Wrote: [ -> ]i use this code to rank a list, the problem is if there is a tie break it gives inaccurate info,
We don't know what you call 'accurate info', so please describe the problem in terms of what the output should be for which input and how the output is related to the input.
Apart from that note that boolean values in Python are
True and
False instead of TRUE and FALSE that you used. Also you don't need to import tkinter.
I think same values should have the same rank. Like this:
from numpy import array from scipy.stats import rankdata import pandas as pd a = array([2, -3, -1, 4, 5, 4, 6]) for value, rank in zip(a, rankdata(a)): # used rankdata(a, method='ordinal') for tie breaking print(f"{value:2}, Rank = {int(rank)}") df = pd.DataFrame({"Value": a}) df["Rank"] = df["Value"].rank().astype(int) print(df) a = [2, -3, -1, 4, 5, 4, 6] ranks = [(value, sorted(a).index(value) + 1) for value in a] print(ranks)Output:
2, Rank = 3 -3, Rank = 1 -1, Rank = 2 4, Rank = 4 # Both 4's have same rank 5, Rank = 6 # Notice there is no rank = 5 4, Rank = 4 6, Rank = 7 Value Rank 0 2 3 1 -3 1 2 -1 2 3 4 4 4 5 6 5 4 4 6 6 7 [(2, 3), (-3, 1), (-1, 2), (4, 4), (5, 6), (4, 4), (6, 7)]
I found the solution so thought i would post it back here.
import numpy as np a = np.array([2,-3,-1,4,5,4,6]) sorted_indices = np.argsort(a) ranks = np.empty_like(sorted_indices) ranks[sorted_indices] = np.arange(len(a)) print(ranks)