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

3

我想创建一个大小为 (10000, 50) 的数组(我提到大小是因为效率很重要),然后:

  • 将前 5000 行按升序排序
  • 将后 5000 行按降序排序。

这是我的代码:

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)

这将对数组的一半按升序排序,唯一找不到的是在最后一行中给出参数以使其按降序排列。我已经根据此链接尝试过:Reverse sort a 2d numpy array in python
xx[halfSamples:samples,0:sampleLength]=numpy.sort(xx[halfSamples:samples,0:sampleLength:-1],axis=1)

但是遇到了一个错误:
ValueError: could not broadcast input array from shape (5,0) into shape (5,4)

谢谢


3
需要在最后一行加上[:,::-1]吗?该操作将对该行的数组进行反转。 - Divakar
1个回答

4

使用数组的 .sort 方法进行就地排序可能会更快,而不是使用返回副本的 np.sort。您可以使用负步长索引第二个维度,以按降序对最后5000行的列进行排序:

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

-5000的意思是什么,为什么它和5000:10000一样? - OopsUser
负索引是相对于数组的末尾,所以x[-5000:]从数组末尾往前索引第5000行。x[-1]会给你最后一行,x[-10:]会给你最后10行,依此类推。 - ali_m

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接