簡體   English   中英

二維 Python 數組排序:對具有相同第二個值的第一個進行排序

[英]Two Dimensional Python Array Sort: Sort the first having the same second values

我目前正在處理坐標,不知何故,我需要按具有相同 y 坐標的升序對 x 坐標進行排序,而不觸及 y 坐標。

這是示例輸入:

x = [213,212,213,214,215,216,215,216,217,216,218,217,219,220,219]
y = [352,333,332,330,328,327,327,326,325,325,324,324,323,322,322]
xy = np.array([x,y])

這是所需的 output:

x = [213,212,213,214,215,215,216,216,216,217,217,218,219,219,220]
y = [352,333,332,330,328,327,327,326,325,325,324,324,323,322,322]

注意:我一直在尋找這個,但我似乎找不到直接的答案。 謝謝你。

您可以先制作一個配對列表,並按第一個坐標對其進行排序,然后將其放入 numpy 數組

>>> x = [213,212,213,214,215,216,215,216,217,216,218,217,219,220,219]
>>> y = [352,333,332,330,328,327,327,326,325,325,324,324,323,322,322]
>>> xy=sorted(zip(x,y),key=lambda pair:pair[0])
>>> xy
[(212, 333), (213, 352), (213, 332), (214, 330), (215, 328), (215, 327), (216, 327), (216, 326), (216, 325), (217, 325), (217, 324), (218, 324), (219, 323), (219, 322), (220, 322)]
>>> nxy = np.array(xy).T
>>> nxy
array([[212, 213, 213, 214, 215, 215, 216, 216, 216, 217, 217, 218, 219,
        219, 220],
       [333, 352, 332, 330, 328, 327, 327, 326, 325, 325, 324, 324, 323,
        322, 322]])
>>> nxy
array([[212, 213, 213, 214, 215, 215, 216, 216, 216, 217, 217, 218, 219,
        219, 220],
       [333, 352, 332, 330, 328, 327, 327, 326, 325, 325, 324, 324, 323,
        322, 322]])
>>> 

經過一些好的舊試驗和錯誤后找到一種方法將它們排序為 numpy

>>> x = [0, 500, 100, 300, 200, 800, 400, 600, 700, 900]
>>> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> xy= np.array([x,y])
>>> xy
array([[  0, 500, 100, 300, 200, 800, 400, 600, 700, 900],
       [  0,   1,   2,   3,   4,   5,   6,   7,   8,   9]])
>>> np.argsort(xy[0]) #get an array with the index that correspond to the elements in a sorted fashion 
array([0, 2, 4, 3, 6, 1, 7, 8, 5, 9], dtype=int64)
>>> xy[:,np.argsort(xy[0])] #ask for the elements in the aforementioned order, while preserving their pairing
array([[  0, 100, 200, 300, 400, 500, 600, 700, 800, 900],
       [  0,   2,   4,   3,   6,   1,   7,   8,   5,   9]])
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM