Ranking of numpy array with possible duplicates

前端 未结 3 2193
你的背包
你的背包 2021-01-17 22:00

I have a numpy array of floats/ints and want to map its elements into their ranks.

If an array doesn\'t have duplicates the problem can be solved by the following co

3条回答
  •  猫巷女王i
    2021-01-17 22:41

    You can do reasonably well using unique and bincount:

    >>> u, v = np.unique(a2, return_inverse=True)
    >>> (np.cumsum(np.bincount(v)) - 1)[v]
    array([0, 3, 4, 5, 6, 3, 7, 9, 9, 3])
    

    Or, for the minimum rank:

    >>> (np.cumsum(np.concatenate(([0], np.bincount(v)))))[v]
    array([0, 1, 4, 5, 6, 1, 7, 8, 8, 1])
    

    There's a minor speedup by giving bincount the number of bins to provide:

    (np.cumsum(np.bincount(v, minlength=u.size)) - 1)[v]
    

提交回复
热议问题