2011-02-18 55 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])