1

I have a following 2D numpy array:

array([[1 0]
       [2 0]
       [4 0]
       [1 1]
       [2 1]
       [3 1]
       [4 2])

I want to sort the ID of first column with its value in second value, suck that I get back:

array([[1 0]
       [1 1]
       [2 0]
       [2 1]
       [3 1]
       [4 0]
       [4 2]])

I am getting O(n^2) complexity and want to improve it further.

3
  • 1
    Have you tried using numpy sort het.as.utexas.edu/HET/Software/Numpy/reference/generated/… ? Commented Sep 11, 2019 at 10:46
  • Can you please show your solution? Commented Sep 11, 2019 at 10:47
  • @Austin this is just 2 column in my data, if I show you my solution, I has to fix all question Commented Sep 11, 2019 at 10:49

2 Answers 2

1

A better way to sort a list of lists:

import numpy as np
a = np.array([[1, 0], [2 ,0], [4 ,0], [1 ,1], [2 ,1], [3 ,1], [4 ,2]])
s_a = np.asarray(sorted(a, key=lambda x: x[0]))
print(s_a)

Output:

[[1 0]
 [1 1]
 [2 0]
 [2 1]
 [3 1]
 [4 0]
 [4 2]]
Sign up to request clarification or add additional context in comments.

1 Comment

@Cuz.I'm.BatMan You're welcome, I'm glad to be helpful.
1

Try the below code, Hope this will help:

a = np.array([[1, 0],
       [2 ,0],
       [4 ,0],
       [1 ,1],
       [2 ,1],
       [3 ,1],
       [4 ,2]])

np.sort(a.view('i8,i8'), order=['f0'], axis=0).view(np.int)

Ouput will be :

array([[(1, 0)],
       [(1, 1)],
       [(2, 0)],
       [(2, 1)],
       [(3, 1)],
       [(4, 0)],
       [(4, 2)]])

2 Comments

I got this bug 'ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.'
@Cuz.I'm.BatMan Please upvote and accept my answer, if it works for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.