Efficient method to calculate the rank vector of a list in Python

后端 未结 11 955
温柔的废话
温柔的废话 2020-12-02 20:06

I\'m looking for an efficient way to calculate the rank vector of a list in Python, similar to R\'s rank function. In a simple list with no ties between the ele

11条回答
  •  醉话见心
    2020-12-02 20:56

    import numpy as np
    
    def rankVec(arg):
        p = np.unique(arg) #take unique value
        k = (-p).argsort().argsort() #sort based on arguments in ascending order
        dd = defaultdict(int)
        for i in xrange(np.shape(p)[0]):
            dd[p[i]] = k[i]
        return np.array([dd[x] for x in arg])
    

    timecomplexity is 46.2us

提交回复
热议问题