pistal
pistal

Reputation: 2454

Ranking data in python without numpy

Is there a way in python (without numpy) to rank lists? for example:

array1 = [1934,1232,345453,123423423,23423423,23423421]
array = [4,2,7,1,1,2]
ranks = [2,1,3,0,0,1]

Gives me examples only with numpy.

I would primarily like to rank the data and then process the data based on ranks to see which dataelements in array1 contribute to 90% of the highest data in array.

Let me know if you want me to give an example.

Upvotes: 0

Views: 2462

Answers (1)

DSM
DSM

Reputation: 353604

IIUC you can build a rank dictionary easily enough, and then loop over the elements of array to find the ranks:

>>> array = [4,2,7,1,1,2]
>>> rankdict = {v: k for k,v in enumerate(sorted(set(array)))}
>>> rankdict
{1: 0, 2: 1, 4: 2, 7: 3}
>>> ranked = [rankdict[a] for a in array]
>>> ranked
[2, 1, 3, 0, 0, 1]

If you want to sort array1 by this ranking, there are several ways to do it. One common one is to build a zipped list and then sort that:

>>> zip(ranked, array)
[(2, 4), (1, 2), (3, 7), (0, 1), (0, 1), (1, 2)]
>>> sorted(zip(ranked, array))
[(0, 1), (0, 1), (1, 2), (1, 2), (2, 4), (3, 7)]
>>> sorted(zip(ranked, array1))
[(0, 23423423), (0, 123423423), (1, 1232), (1, 23423421), (2, 1934), (3, 345453)]

Upvotes: 1

Related Questions