2

I have created 2 variables. One to hold 200 randomly generated ages, the other to hold 200 randomly generated marks.

from numpy import *
age = random.random_integers(18,40, size=(1,200))
marks = random.random_integers(0,100, size=(1,200))

I'd like to use NumPy to sort the marks array by the age array. eg:

#random student ages
[32 37 53 48 39 44 33 40 56 47]
#random student marks
[167 160 176 163 209 178 201 164 190 156]

#sorted marked according to ages
[32 33 37 39 40 44 47 48 53 56]
[167 201 160 209 164 178 156 163 176 190]

It is a similar question to this one. I am just unsure if a similar solution applies due to the elements being randomly generated.

3
  • 1
    yes your linked answer does apply to your situation.. in your case you would sort marks according to age with: sorted_marks = marks[age.argsort()]. For this to work smoothly however you should eliminate the extraneous axis in your array by using size=200 instead of size=(1,200) Commented May 29, 2018 at 13:35
  • 2
    Possible duplicate of How can I "zip sort" parallel numpy arrays? Commented May 29, 2018 at 13:39
  • better example Commented May 29, 2018 at 13:42

1 Answer 1

2

One way is to first calculate an ordering via argsort, then use this to index your input arrays::

import numpy as np

np.random.seed(0)

ages = np.random.randint(18, 40, size=10)   # [30 33 39 18 21 21 25 27 37 39]
marks = np.random.randint(0, 100, size=10)  # [36 87 70 88 88 12 58 65 39 87]

order = ages.argsort()                      # [3 4 5 6 7 0 1 8 2 9]

print(ages[order])                          # [18 21 21 25 27 30 33 37 39 39]
print(marks[order])                         # [88 88 12 58 65 36 87 39 70 87]
Sign up to request clarification or add additional context in comments.

2 Comments

Correct me if I'm wrong, but this does not do, what OP intended since it sorts the rows of the stacked array independently.
@Christoph90, Good spot, I've corrected the answer now.

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.