2016-07-30 84 views
3

我試圖創建一個數組(10000,50),大小(我提到的大小,因爲效率是很重要的),然後輸入:如何排序一半的二維數組大小排序(numpy的)

  • 按升序對前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

回答

4

它可能會更快使用到位數組排序它的方法是.sort,而不是np.sort,它返回一個副本。您可以使用指數負步長到最後5000行的降序對列進行排序的第二個維度:

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

-5000是什麼意思,爲什麼它和5000:10000一樣? – OopsUser

+0

負索引相對於數組的末尾,所以'x [-5000:]'索引從數組末尾開始的第5000行。 'x [-1]'會給你最後一行,'x [-10:]'會給你最後10行等。 –

+0

很好的答案,謝謝 – OopsUser