Skip to content

Commit

Permalink
BUG: ticket numpy#2063, make unique return consistent index.
Browse files Browse the repository at this point in the history
Make unique use  mergesort when return_index is true. This quarantees that
the returned indices are of the first occurrence of the unique elements and
makes the behavior better defined and consistent.
  • Loading branch information
Bryan Van de Ven authored and charris committed Apr 27, 2012
1 parent b452014 commit 74b9f5e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
9 changes: 9 additions & 0 deletions numpy/core/tests/test_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -1611,5 +1611,14 @@ def test_assign_obj_listoflists(self):
a[...] = [[1,2]]
assert_equal(a, [[1,2], [1,2]])

def test_unique_stable(self):
# Ticket #2063 must always choose stable sort for argsort to
# get consistent results
v=np.array([0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2]*4)
w=np.array([0,0,0,0,0,1,1,1,1,1,1,2,2,2,2])
resv = np.unique(v,return_index=True)
resw = np.unique(w,return_index=True)
assert_equal(resv, resw)

if __name__ == "__main__":
run_module_suite()
9 changes: 6 additions & 3 deletions numpy/lib/arraysetops.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ def unique(ar, return_index=False, return_inverse=False):
unique : ndarray
The sorted unique values.
unique_indices : ndarray, optional
The indices of the unique values in the (flattened) original array.
Only provided if `return_index` is True.
The indices of the first occurrences of the unique values in the
(flattened) original array. Only provided if `return_index` is True.
unique_inverse : ndarray, optional
The indices to reconstruct the (flattened) original array from the
unique array. Only provided if `return_inverse` is True.
Expand Down Expand Up @@ -174,7 +174,10 @@ def unique(ar, return_index=False, return_inverse=False):
return ar

if return_inverse or return_index:
perm = ar.argsort()
if return_index:
perm = ar.argsort(kind='mergesort')
else:
perm = ar.argsort()
aux = ar[perm]
flag = np.concatenate(([True], aux[1:] != aux[:-1]))
if return_inverse:
Expand Down

0 comments on commit 74b9f5e

Please sign in to comment.