简体   繁体   English

如何按降序对二维数组中的一半进行排序(numpy)

[英]How to sort half of the 2d array in descending order (numpy)

I'm trying to create an array (10000, 50) size (I'm mentioning the size because efficiency is important), and then : 我正在尝试创建一个数组(10000,50)大小(我提到大小因为效率很重要),然后:

  • Sort the first 5000 rows in ascending order 按升序对前5000行进行排序
  • Sort the next 5000 rows in descending order. 按降序对接下来的5000行进行排序。

Here is my code : 这是我的代码:

samples = 10  # I'm going to increase it 10000
sampleLength = 4 # I'm going to increase it 50
halfSamples = int(samples/2)

xx = numpy.multiply(10, numpy.random.random((samples, sampleLength)))
xx[0:halfSamples,0:sampleLength]=numpy.sort(xx[0:halfSamples,0:sampleLength],axis=1)
xx[halfSamples:samples,0:sampleLength]=numpy.sort(xx[halfSamples:samples,0:sampleLength],axis=1)

This sorts both half of the array in ascending order, the only thing I can't find is what parameter to give in my last line to make it in a descending order. 这按照升序对数组的一半进行排序,我唯一找不到的是在我的最后一行中给出的参数是按降序排列的。

I've tried based on this link : Reverse sort a 2d numpy array in python 我试过基于这个链接: 在python中反向排序一个2d numpy数组

xx[halfSamples:samples,0:sampleLength]=numpy.sort(xx[halfSamples:samples,0:sampleLength:-1],axis=1)

But got an error : 但是得到了一个错误:

ValueError: could not broadcast input array from shape (5,0) into shape (5,4)

Thanks 谢谢

It would probably be faster to sort the array in place using its .sort method, rather than np.sort which returns a copy. 使用.sort方法对数组进行排序可能会更快,而不是返回副本的np.sort You can index the second dimension using a negative step size to sort the columns of the last 5000 rows in descending order: 您可以使用负步长索引第二个维度,以按降序对最后5000行的列进行排序:

x = np.random.randn(10000, 50)
x[:5000].sort(axis=1)
x[-5000:, ::-1].sort(axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM