Search code examples
pythonarrayssortingnumpylexicographic

How to sort a 2D numpy array lexicographically by one column?


how to sort numpy 2D array with 2 elements: For example I have:

[['0.6435256766173603' 'some text']
 ['0.013180497307149886' 'some text2']
 ['0.017696632827641112' 'some text3']]  
I need:
[['0.6435256766173603' 'some text']
 ['0.017696632827641112' 'some text3']
 ['0.013180497307149886' 'some text2']] 

I tried np.argsort, np.sort, but it doesn't work! Any help will be appreciated


Solution

  • Assuming you want your array lexsorted by the 0th column, np.argsort is what you want.

    out = x[np.argsort(x[:, 0])[::-1]]
    print(out)
    

    array([['0.6435256766173603', 'some text'],
           ['0.017696632827641112', 'some text3'],
           ['0.013180497307149886', 'some text2']],