0

I have a 2D numpy array and I would like to sort the rows based on first column values. The trouble is the way it is formatted:

Column I am sorting by: 0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,etc ->you can see it repeats itself

Basically I want to group the 1s, then 2s, then 3s, then 4s. The ordering of the matching values matter: I want the 1st '1' row to be the first one that appeared in the unsorted array, followed by the one that shows up next, etc. I use this command: sortedData= myData[myData[:,0].argsort()]

Unfortunately, it doesn't not appear to order matching columns based on the original ordering of the array. Are there certain options I can turn on to enable this?

Thanks!

1 Answer 1

3

You can change the sorting algorithm used by argsort with the kind argument.

Use

sortedData= myData[myData[:,0].argsort(kind='mergesort')]

to preserve the order of the equal items. (Merge sort is a stable sorting algorithm.)

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

1 Comment

As per numpy v.1.15.0, select kind="stable"`. mergesort`` is just for backwards compatibility. numpy.org/doc/stable/reference/generated/numpy.argsort.html

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.