以降序对numpy数组进行有效排序? [英] Efficiently sorting a numpy array in descending order?

查看:41
本文介绍了以降序对numpy数组进行有效排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶之前没有人问过这个特定的问题,但我真的没有在 SO 和 np.sort 的文档中找到它.

I am surprised this specific question hasn't been asked before, but I really didn't find it on SO nor on the documentation of np.sort.

假设我有一个包含整数的随机 numpy 数组,例如:

Say I have a random numpy array holding integers, e.g:

> temp = np.random.randint(1,10, 10)    
> temp
array([2, 4, 7, 4, 2, 2, 7, 6, 4, 4])

如果我排序,默认是升序:

If I sort it, I get ascending order by default:

> np.sort(temp)
array([2, 2, 2, 4, 4, 4, 4, 6, 7, 7])

但我希望解决方案按降序排序.

but I want the solution to be sorted in descending order.

现在,我知道我总能做到:

Now, I know I can always do:

reverse_order = np.sort(temp)[::-1]

但这最后一条语句有效吗?不是按升序创建一个副本,然后反转这个副本以获得相反顺序的结果吗?如果确实如此,是否有有效的替代方案?看起来 np.sort 不接受参数来改变排序操作中比较的符号以得到相反的顺序.

but is this last statement efficient? Doesn't it create a copy in ascending order, and then reverses this copy to get the result in reversed order? If this is indeed the case, is there an efficient alternative? It doesn't look like np.sort accepts parameters to change the sign of the comparisons in the sort operation to get things in reverse order.

推荐答案

temp[::-1].sort() 对数组进行原地排序,而 np.sort(temp)[::-1] 创建一个新数组.

temp[::-1].sort() sorts the array in place, whereas np.sort(temp)[::-1] creates a new array.

In [25]: temp = np.random.randint(1,10, 10)

In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

In [27]: id(temp)
Out[27]: 139962713524944

In [28]: temp[::-1].sort()

In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

In [30]: id(temp)
Out[30]: 139962713524944

这篇关于以降序对numpy数组进行有效排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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