Python Ranking Dictionary Return Rank

前端 未结 7 1365
我在风中等你
我在风中等你 2021-02-10 06:40

I have a python dictionary:

x = {\'a\':10.1,\'b\':2,\'c\':5}

How do I go about ranking and returning the rank value? Like getting back:

7条回答
  •  盖世英雄少女心
    2021-02-10 06:57

    Using scipy.stats.rankdata:

    [ins] In [55]: from scipy.stats import rankdata                                                                                                                                                        
    
    [ins] In [56]: x = {'a':10.1, 'b':2, 'c': 5, 'd': 5}                                                                                                                                                   
    
    [ins] In [57]: dict(zip(x.keys(), rankdata([-i for i in x.values()], method='min')))                                                                                                                   
    Out[57]: {'a': 1, 'b': 4, 'c': 2, 'd': 2}
    
    [ins] In [58]: dict(zip(x.keys(), rankdata([-i for i in x.values()], method='max')))                                                                                                                   
    Out[58]: {'a': 1, 'b': 4, 'c': 3, 'd': 3}
    

    @beta, @DSM scipy.stats.rankdata has some other 'methods' for ties also that may be more appropriate to what you are wanting to do with ties.

提交回复
热议问题