2015-05-03 141 views
1

numpy.partition()也排序數組的內部元素。numpy.partition()with 2-D Array

我一直在嘗試基於數組的所有元素的第一個元素進行簡單的排序。

import numpy as np 
a = np.array([[5.2, 4.3], [200.2, 6.2], [1.4, 112.2]]) 
np.partition(a, (1,a.shape[1]-1), axis = 1) 

輸出:

array([[ 4.3, 5.2], 
     [ 6.2, 200.2], 
     [ 1.4, 112.2]]) 

我不明白這裏的np.partition()工作。任何資源的詳細信息numpy.partition()

具體而言,我要修改的方法的參數,以產生以下輸出:

array([[ 1.4, 112.2], 
     [ 5.2, 4.3], 
     [ 200.2, 6.2]]) 

回答

2

如果我理解正確,您只需根據第一列中的值對數組中的行進行排序。您可以使用np.argsort做到這一點:

# get an array of indices that will sort the first column in ascending order 
order = np.argsort(a[:, 0]) 

# index into the row dimension of a 
a_sorted = a[order] 

print(a_sorted) 
# [[ 1.4 112.2] 
# [ 5.2 4.3] 
# [ 200.2 6.2]] 

如果你想有一個局部排序,而不是一個完整的排序,你可以在很多使用np.argpartition以同樣的方式:

# a slightly larger example array in order to better illustrate what 
# argpartition does 
b = np.array([[ 5.2, 4.3], 
       [200.2, 6.2], 
       [ 3.6, 85.1], 
       [ 1.4, 112.2], 
       [ 12.8, 60.0], 
       [ 7.6, 23.4]]) 

# get a set of indices to reorder the rows of `b` such that b[2, 0] is in its 
# final 'sorted' position, and all elements smaller or larger than it will be 
# placed before and after it respectively 
partial_order = np.argpartition(b[:, 0], 2) 

# the first (2+1) elements in the first column are guaranteed to be smaller than 
# the rest, but apart from that the order is arbitrary 
print(b[partial_order]) 
# [[ 1.4 112.2] 
# [ 3.6 85.1] 
# [ 5.2 4.3] 
# [ 200.2 6.2] 
# [ 12.8 60. ] 
# [ 7.6 23.4]] 
+0

我可以用numpy.partition()方法做同樣的事情。原因是,我有大約18000行的數據集,我想分割它。但是這種分區方法正在混洗值。 – user2831683

+0

如果您只想部分按第一列進行排序,則可以使用['np.argpartition'](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html)在我上面的例子中'np.argsort'。 –

3

np.partition()確保在特定索引值是相同的,因爲它們是,如果該陣列將被完全排序(例如與np.sort)。 (其他索引值的順序不保證是有意義的。)

axis=1參數表示此操作將單獨應用於每行。

在這裏,您通過的索引是(1, a.shape[1]-1),在這種情況下相當於(1, 1)。重複索引沒有特殊含義,因此在每一行中,第二列(索引1)中的值將與每行按排序順序相同。

現在,應用操作時,您會在返回的數組中看到第一行和第二行中的較高值已移至此第二列。第三行已經按照排序順序排列,因此不變。

這真的是所有的功能:NumPy documentation涵蓋了一些進一步的細節。如果你感覺特別勇敢,你可以找到源代碼實現np.partition()所使用的所有榮耀here的introselect算法。

+0

我可以阻止內部元素的順序,由該方法完成。 – user2831683

+0

我不太確定你的意思 - 你能詳細說明一下嗎? –

+0

我編輯了這個問題,更具體的 – user2831683