0

Data set we have is here.

a=np.array([2,6,9,5])
b =np.array([0.5,3,1,4])

what I'm looking for is (sorted data points by a)

a=np.array([2,5,6,9])
b =np.array([0.5,4,3,1])

The code I've been trying and gives me an error

If you can teach me the error, it would be very appreciable. I search answers for this, but I couldn't find out. Thank you so much in advance.

import numpy as np
a=np.array([2,6,9,5])
b =np.array([0.5,3,1,4])

#transpose data points
datatemp = np.array([a, b]).T

data=sorted(datatemp, key=itemgetter(0))

a=data[:,0]
b=data[:,1]
print(a)
print(b)
pault
  • 41,343
  • 15
  • 107
  • 149
mocs
  • 101
  • 10

1 Answers1

2

You don't actually need to do any of this crazy transpose stuff. The function np.argsort() is designed for this kind of stuff.

a = np.array([2,6,9,5])
b = np.array([0.5,3,1,4])
arg_order = np.argsort(a)

a = a[arg_order]
b = b[arg_order]

print(a)
print(b)
#: array([2, 5, 6, 9])
#: array([ 0.5,  4. ,  3. ,  1. ])

If you look at the value of arg_order, all it is is an array of which indexes to retrieve in the correct order.

print(arg_order)
#: array([0, 3, 1, 2])

Numpy arrays can take arrays as index arguments which describe what order to retrieve what elements in. (Give me a new array with the 0th, then the 3rd, then the 1st then the 2nd elements in that order).

SCB
  • 5,821
  • 1
  • 34
  • 43