ranking - Python -- rank tuples by first item, resolve ties by second item -
i have following list of tuples:
[(1, 6), (2, 3), (2, 5), (2, 2), (1, 7), (3, 2), (2, 2)]
i rank list first value in tuple , resolve ties second value, output looks this:
[1, 5, 6, 3, 2, 7, 3]
i couldn't think of simple way of doing this, looking scipy.stats.rankdata function. however, use-case it's missing order argument in numpy.argsort. feel i'm missing obvious here, in case apologise not googling answer better!
edit:
to explain better trying achieve:
given list of tuples
>>> l = [(1, 6), (2, 3), (2, 5), (2, 2), (1, 7), (3, 2), (2, 2)]
i want create list containing rank of elements of list l. example, ranking first value in each tuple:
>>> scipy import stats >>> stats.rankdata([i i, j in l], method='min') array([ 1., 3., 3., 3., 1., 7., 3.])
this wanted, there ties in list (there's 2 times 1. , 4 times 3.).
i break ties using second value in each tuple, example 2 tuples (2, 2) have same rank, (2, 3) , (2, 5) have different rank. resulting list should this:
array([ 1., 5., 6., 3., 2., 7., 3.])
python sorts sequences naturally.
>>> [x x, y in sorted(enumerate([(1, 6), (2, 3), (2, 5), (2, 2), (1, 7), (3, 2), (2, 2)], start=1), key=operator.itemgetter(1))] [1, 5, 4, 7, 2, 3, 6]
Comments
Post a Comment