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.

hR 312
  • 824
  • 1
  • 9
  • 22
CuCaRot
  • 1,208
  • 7
  • 23

2 Answers2

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)]])
Shishir Naresh
  • 743
  • 4
  • 10
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]]
Hu Xixi
  • 1,799
  • 2
  • 21
  • 29