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
  • 804
  • 8
  • 21
CuCaRot
  • 780
  • 6
  • 17

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
  • 718
  • 4
  • 9
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,551
  • 16
  • 25