【问题标题】:How to sort half of the 2d array in descending order (numpy)如何按降序对二维数组的一半进行排序(numpy)
【发布时间】:2016-12-05 07:21:39
【问题描述】:

我正在尝试创建一个数组 (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)

谢谢

【问题讨论】:

  • 在最后一行末尾追加[:,::-1]

标签: python arrays sorting numpy


【解决方案1】:

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

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

【讨论】:

  • -5000是什么意思,为什么和5000:10000一样?
  • 负索引是相对于数组末尾的,因此x[-5000:] 从数组末尾开始索引第 5000 行。 x[-1] 会给你最后一行,x[-10:] 会给你最后 10 行等等。
猜你喜欢
  • 2021-12-06
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多