Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rank an array of tuples

Tags:

python

ranking

I have an array

array = [('item1',90),('item2',76),('item3',83),('item4',90)]

and I'd like to rank it like

ranking = [(0,'item1'),(0,'item4'),(2,'item3'),(3,'item2')] // (1)

This is what I've done it so far, using ranking:

from ranking import *

>>> array.sort(key=lambda x: x[1],reverse = True)
>>> print [i for i in list(Ranking([i[1] for i in array]))]

This is what I get:

[(0, 90), (0, 90), (2, 83), (3, 76)] // (2)

Can anyone help me to get from (2) to (1)? I don't really need to use ranking. I accept any other solution.

like image 892
Bruno Calza Avatar asked Oct 28 '25 10:10

Bruno Calza


2 Answers

You can use a Pandas DataFrame to do this. I'd recommend this solution as it's very semantically designed for the purpose for which you wish to put it:

import pandas as pd
df = pd.DataFrame.from_records([('item1',90),('item2',76),
                                ('item3',83),('item4',90)])

Here's the raw dataframe, before we manipulate it:

>>> df
       0   1
0  item1  90
1  item2  76
2  item3  83
3  item4  90

Now we'll select column 1 and rank it descending, and add the rank back into the dataframe (using the min method):

>>> df['rank'] = df[1].rank(method='min', ascending=False)
>>> df
       0   1  rank
0  item1  90     1
1  item2  76     4
2  item3  83     3
3  item4  90     1

Now we'll convert our desired columns back into a list of tuples, excluding the index:

>>> l = list(df[[0, 'rank']].to_records(index=False))
>>> l
[('item1', 1.0), ('item2', 4.0), ('item3', 3.0), ('item4', 1.0)]

We can get it into the desired state with a list comprehension:

>>> l2 = [(i, int(j-1)) for i, j in l]
>>> l2
[('item1', 0), ('item2', 3), ('item3', 2), ('item4', 0)]
like image 161
Russia Must Remove Putin Avatar answered Oct 30 '25 01:10

Russia Must Remove Putin


array = [('item1',90),('item2',76),('item3',83),('item4',90)]
srt = sorted(array,key=lambda x: x[1], reverse=True)
rankings = []
rank = 0
from itertools import groupby
for k,v in groupby(srt,lambda x: x[1]): # group by score
    grp = [(rank,tup[0]) for tup in v] # get item tup[0] and put it in a tuple with the rank
    rankings += grp
    rank += len(grp) # increase rank for next grouping
print(rankings)
[(0, 'item1'), (0, 'item4'), (2, 'item3'), (3, 'item2')]
like image 42
Padraic Cunningham Avatar answered Oct 30 '25 01:10

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!