[英]Python (Numpy) array sorting
我有一個名為v的dtype('float64')數組:
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(axis = 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]])
......每條線的元素沒有相對移動。
嘗試
v[v[:,0].argsort()]
( v
是數組)。 v[:,0]
是第一列, .argsort()
返回將對第一列進行排序的索引。 然后使用高級索引將此排序應用於整個數組。 請注意,您將獲得該陣列的sorte副本。
我知道對數組進行排序的唯一方法是使用記錄dtype:
v.dtype = [("x", float), ("y", float), ("z", float)]
v.shape = v.size
v.sort(order="x")
另外
嘗試
import numpy as np
order = v[:, 0].argsort()
sorted = np.take(v, order, 0)
'order'具有第一行的順序。 然后'np.take'將列按相應的順序排列。
請參閱'np.take'的幫助
help(np.take)
take(a,indices,axis = None,out = None,mode ='raise')沿軸取一個數組中的元素。
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])
如果你有v[:,0]
有一些相同值的實例,你想對第1,2列等進行二次排序,那么你將需要使用numpy.lexsort()
或numpy.sort(v, order=('col1', 'col2', etc..)
但是對於order=
case, v
將需要是一個結構化數組。
numpy.lexsort()
一個示例應用程序,用於對數組的行進行排序並處理第一列中的關系。 需要注意的是lexsort
有效排序列,並與最后一列開始,所以你需要扭轉的行a
對前再取轉lexsort
,最后轉置的結果(你會認為這應該是比較容易的,但哎!) :
In [1]: import numpy as np
In [2]: a = np.array([[1,2,3,4],[1,0,4,1],[0,4,1,1]])
In [3]: a[np.lexsort(np.flip(a, axis=1).T).T]
Out[3]:
array([[0, 4, 1, 1],
[1, 0, 4, 1],
[1, 2, 3, 4]])
In [4]: a
Out[4]:
array([[1, 2, 3, 4],
[1, 0, 4, 1],
[0, 4, 1, 1]])
感謝@Paul提出使用lexsort
的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.