2011-02-18 78 views
7

我有了這個數組,命名爲V,D類的( 'float64'):的Python(NumPy的)數組排序

array([[ 9.33350000e+05, 8.75886500e+06, 3.45765000e+02], 
     [ 4.33350000e+05, 8.75886500e+06, 6.19200000e+00], 
     [ 1.33360000e+05, 8.75886500e+06, 6.76650000e+02]]) 

...我已經從文件中使用NP收購。 loadtxt命令。我想按照第一列的值排序它,而不會混淆保持同一行上列出的數字的結構。使用v.sort(軸= 0)給我:

array([[ 1.33360000e+05, 8.75886500e+06, 6.19200000e+00], 
     [ 4.33350000e+05, 8.75886500e+06, 3.45765000e+02], 
     [ 9.33350000e+05, 8.75886500e+06, 6.76650000e+02]]) 

...即放置在第一行第三列的數量最少,等我寧願希望這樣的事情...

array([[ 1.33360000e+05, 8.75886500e+06, 6.76650000e+02], 
     [ 4.33350000e+05, 8.75886500e+06, 6.19200000e+00], 
     [ 9.33350000e+05, 8.75886500e+06, 3.45765000e+02]]) 

......其中每一行的元素沒有相對移動。

回答

13

嘗試

v[v[:,0].argsort()] 

(與v是陣列)。 v[:,0]是第一列,而​​返回將對第一列進行排序的索引。然後使用高級索引將此順序應用於整個陣列。請注意,您將獲得數組的一個分類副本。

我知道的到位數組排序的唯一方法是使用記錄D型:如果你有實例,其中v[:,0]有一些相同的價值觀和你想二次排序1列

v.dtype = [("x", float), ("y", float), ("z", float)] 
v.shape = v.size 
v.sort(order="x") 
5

或者

嘗試

import numpy as np 

order = v[:, 0].argsort() 
sorted = np.take(v, order, 0) 

'秩序' 的第一行的順序。 ,然後'np.take'將列對應的順序。

參見 'np.take' 的幫助下

help(np.take) 

取(一個,指數,軸=無,OUT =無, 模式= '加註') 取元件從數組沿軸線。

This function does the same thing as "fancy" indexing (indexing arrays 
using arrays); however, it can be easier to use if you need elements 
along a given axis. 

Parameters 
---------- 
a : array_like 
    The source array. 
indices : array_like 
    The indices of the values to extract. 
axis : int, optional 
    The axis over which to select values. By default, the flattened 
    input array is used. 
out : ndarray, optional 
    If provided, the result will be placed in this array. It should 
    be of the appropriate shape and dtype. 
mode : {'raise', 'wrap', 'clip'}, optional 
    Specifies how out-of-bounds indices will behave. 

    * 'raise' -- raise an error (default) 
    * 'wrap' -- wrap around 
    * 'clip' -- clip to the range 

    'clip' mode means that all indices that are too large are 

由地址沿該軸的最後一個元素的索引代替 。注意 ,這將禁用索引與負數。

Returns 
------- 
subarray : ndarray 
    The returned array has the same type as `a`. 

See Also 
-------- 
ndarray.take : equivalent method 

Examples 
-------- 
>>> a = [4, 3, 5, 7, 6, 8] 
>>> indices = [0, 1, 4] 
>>> np.take(a, indices) 
array([4, 3, 6]) 

In this example if `a` is an ndarray, "fancy" indexing can be used. 

>>> a = np.array(a) 
>>> a[indices] 
array([4, 3, 6])