0

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

1
  • You have a numpy.ndarray with strings? You should probably just use normal Python lists... Commented Sep 19, 2017 at 0:27

2 Answers 2

3

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']],
Sign up to request clarification or add additional context in comments.

Comments

3
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]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.