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

前端 未结 4 1015
半阙折子戏
半阙折子戏 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:47

    I've written a function for the same purpose. It uses pure python and numpy only. Please have a look. I put comments as well.

    def my_argsort(array):
        # this type conversion let us work with python lists and pandas series
        array = np.array(array)
        # create mapping for unique values
        # it's a dictionary where keys are values from the array and
        # values are desired indices 
        unique_values = list(set(array))
        mapping = dict(zip(unique_values, np.argsort(unique_values)))
        # apply mapping to our array
        # np.vectorize works similar map(), and can work with dictionaries
        array = np.vectorize(mapping.get)(array)
        return array
    

    Hope that helps.

提交回复
热议问题