2

I have a few numpy arrays like so:

import numpy as np
a = np.array([[1, 2, 3, 4, 5], [14, 16, 17, 27, 38]])
b = np.array([[1, 2, 3, 4, 5], [.4, .2, .5, .1, .6]])

I'd like to be able to 1.Copy these arrays into a new single array and 2. Sort the data so that the result is as follows:

data = [[1, 1, 2, 2, 3, 3, 4, 4, 5, 5], [14, .4, 16, .2, 17, .5, 27, .1, 38, .6]]

Or, in other words, I need all columns from the original array to be the same, just in an ascending order. I tried this:

data = np.hstack((a,b))

Which gave me the appended data, but I'm not sure how to sort it. I tried np.sort() but it didn't keep the columns the same. Thanks!

4
  • What you describe is not sorting. Commented Jun 12, 2017 at 20:48
  • Then what is and what isn't sorting? Commented Jun 13, 2017 at 12:26
  • You convert [a, b, c], [d, e, f] into [a, d, b, e, c, f], not sorted([a, d, b, e, c, f]). You perform sorting on pairs of zip([a, b, c], [d, e, f]). Commented Jun 13, 2017 at 12:37
  • Yes, but that was my question -- how to go from [a, d, b, e, c, f] to [a, b, c, d, e, f]. Is that not sorting my array? Commented Jun 15, 2017 at 14:20

2 Answers 2

4

Stack those horizontally (as you already did), then get argsort indices for sorting first row and use those to sort all columns in the stacked array.

Thus, we need to add one more step, like so -

ab = np.hstack((a,b))
out = ab[:,ab[0].argsort()]

Sample run -

In [370]: a
Out[370]: 
array([[ 1,  2,  3,  4,  5],
       [14, 16, 17, 27, 38]])

In [371]: b
Out[371]: 
array([[ 1. ,  2. ,  3. ,  4. ,  5. ],
       [ 0.4,  0.2,  0.5,  0.1,  0.6]])

In [372]: ab = np.hstack((a,b))

In [373]: print ab[:,ab[0].argsort()]
[[  1.    1.    2.    2.    3.    3.    4.    4.    5.    5. ]
 [ 14.    0.4  16.    0.2  17.    0.5  27.    0.1  38.    0.6]]

Please note that to keep the order for identical elements, we need to use to use kind='mergesort' with argsort as described in the docs.

Sign up to request clarification or add additional context in comments.

Comments

0

If you like something short.

np.array(zip(*sorted(zip(*np.hstack((a,b))))))

>>> array([[  1. ,   1. ,   2. ,   2. ,   3. ,   3. ,   4. ,   4. ,   5. ,   5. ],
   [  0.4,  14. ,   0.2,  16. ,   0.5,  17. ,   0.1,  27. ,   0.6,  38. ]])

Version that preserve second element order:

np.array(zip(*sorted(zip(*np.hstack((a,b))),key=lambda x:x[0])))

>>>array([[  1. ,   1. ,   2. ,   2. ,   3. ,   3. ,   4. ,   4. ,   5. ,   5. ],
          [ 14. ,   0.4,  16. ,   0.2,  17. ,   0.5,  27. ,   0.1,  38. ,0.6]])

Comments

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.