Sorting a python array/recarray by column

前端 未结 5 1562
旧巷少年郎
旧巷少年郎 2020-12-02 11:33

I have a fairly simple question about how to sort an entire array/recarray by a given column. For example, given the array:

import numpy as np
data = np.a         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 12:12

    Here's an extension that works with slices:

    import numpy as np
    x = np.array([[9, 1, 2],
                  [5, 3, 4],
                  [0, 5, 6]])
    

    Sorting by rows:

    x[:, x[1,:].argsort()] # Sort by second row
    
    array([[1, 2, 9]
           [3, 4, 5]
           [5, 6, 0]])
    

    Sorting by columns:

    x[x[:,0].argsort(), :] # Sort by first column
    
    array([[0, 5, 6],
           [5, 3, 4],
           [9, 1, 2]])
    

提交回复
热议问题