Why is numpy.argsort() shuffeling the indices for ties?

Viewed 148

I am using python 3. The problem is with numpy.argsort().

I have two arrays (say A and B). I want to order values in array A by values in array B. I use this code.

A_ordered = A[B.argsort()]

In array B, there are good chances that ties occur. Sometimes even, every single value in array B is identical.

When there are ties in B, I don't want the values in A to change order. Hence, when values in B are tied, I expect them to keep their relative indices order using .argsort().

Here is an example of the problem when every value in B are tied. Indices given by np.argsort() look like they are shuffled.

B = np.empty(23000) #creating empty array
B.fill(0.5) #filling it with equal values of 0.5
print(B.argsort()) #trying to sort

Out[176]: array([    0, 15338, 15337, ...,  7660,  7680, 22999], dtype=int64)

As all values in B are equal, what I expect is

Out[176]: array([    0, 1, 2, ...,  22997,  22998, 22999], dtype=int64)

I don't want to use the method below for sorting A based on B, because in case of ties, values of A will be used for sorting.

A = [x for _,x in sorted(zip(B,A))]

Many thanks!

1 Answers

You need to tell argsort to use a stable sorting method.

>>> print(B.argsort(kind='stable')) #trying to sort
[    0     1     2 ... 22997 22998 22999]
Related