Can numpy's argsort give equal element the same rank?

前端 未结 4 1017
半阙折子戏
半阙折子戏 2021-02-07 12:04

I want to get the rank of each element, so I use argsort in numpy:

np.argsort(np.array((1,1,1,2,2,3,3,3,3)))
array([0, 1, 2, 3, 4, 5, 6         


        
4条回答
  •  深忆病人
    2021-02-07 12:40

    If you don't mind a dependency on scipy, you can use scipy.stats.rankdata, with method='min':

    In [14]: a
    Out[14]: array([1, 1, 1, 2, 2, 3, 3, 3, 3])
    
    In [15]: from scipy.stats import rankdata
    
    In [16]: rankdata(a, method='min')
    Out[16]: array([1, 1, 1, 4, 4, 6, 6, 6, 6])
    

    Note that rankdata starts the ranks at 1. To start at 0, subtract 1 from the result:

    In [17]: rankdata(a, method='min') - 1
    Out[17]: array([0, 0, 0, 3, 3, 5, 5, 5, 5])
    

    If you don't want the scipy dependency, you can use numpy.unique to compute the ranking. Here's a function that computes the same result as rankdata(x, method='min') - 1:

    import numpy as np
    
    def rankmin(x):
        u, inv, counts = np.unique(x, return_inverse=True, return_counts=True)
        csum = np.zeros_like(counts)
        csum[1:] = counts[:-1].cumsum()
        return csum[inv]
    

    For example,

    In [137]: x = np.array([60, 10, 0, 30, 20, 40, 50])
    
    In [138]: rankdata(x, method='min') - 1
    Out[138]: array([6, 1, 0, 3, 2, 4, 5])
    
    In [139]: rankmin(x)
    Out[139]: array([6, 1, 0, 3, 2, 4, 5])
    
    In [140]: a = np.array([1,1,1,2,2,3,3,3,3])
    
    In [141]: rankdata(a, method='min') - 1
    Out[141]: array([0, 0, 0, 3, 3, 5, 5, 5, 5])
    
    In [142]: rankmin(a)
    Out[142]: array([0, 0, 0, 3, 3, 5, 5, 5, 5])
    

    By the way, a single call to argsort() does not give ranks. You can find an assortment of approaches to ranking in the question Rank items in an array using Python/NumPy, including how to do it using argsort().

提交回复
热议问题