numpy的argsort可以给相同元素相同的等级吗? [英] Can numpy's argsort give equal element the same rank?

查看:200
本文介绍了numpy的argsort可以给相同元素相同的等级吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取每个元素的排名,所以我在numpy中使用argsort:

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, 7, 8])

它给同一元素不同的等级,我可以得到相同的等级吗?

it give the same element the different rank, can I get the same rank like:

array([0, 0, 0, 3, 3, 5, 5, 5, 5])

推荐答案

如果您不介意对scipy的依赖,则可以使用

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])

请注意,rankdata将排名从1开始.要从0开始,请从结果中减去1:

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])


如果您不希望scipy依赖,则可以使用 numpy.unique 来计算排名.这是一个计算与rankdata(x, method='min') - 1相同结果的函数:


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]

例如,

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])


顺便说一句,对argsort()的单次调用不会给出排名.您可以在问题数组使用Python/NumPy ,包括如何使用argsort()来实现.


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().

这篇关于numpy的argsort可以给相同元素相同的等级吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆