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

2.3k views Asked by At

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

2

There are 2 answers

0
this be Shiva On BEST ANSWER

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']],
0
joergd On
a = np.array([['0.6435256766173603', 'some text'],
              ['0.013180497307149886', 'some text2'],
              ['0.017696632827641112', 'some text3']])

a[a[:, 0].argsort()[::-1]]

should yield

array([['0.6435256766173603', 'some text'],
       ['0.017696632827641112', 'some text3'],
       ['0.013180497307149886', 'some text2']],
      dtype='|S20')

Breaking it down:

# the first column of `a`
a[:, 0]  

# sorted indices of the first column, ascending order
a[:, 0].argsort()  # [1, 2, 0]

# sorted indices of the first column, descending order
a[:, 0].argsort()[::-1]  # [0, 2, 1]

# sort `a` according to the sorted indices from the last step
a[a[:, 0].argsort()[::-1]]