-
-
Notifications
You must be signed in to change notification settings - Fork 11k
ENH: Add an "axis" kwarg to numpy.unique #3584
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4fcf6a8
ENH: Add an "axis" kwarg to `numpy.unique`
joferkington a9f8ece
DOC: Fixed typo in docstring examples for unique
joferkington fccd7fe
BUG: unique should raise a clearer error if an invalid axis kwarg is …
joferkington 2544df4
STY: Refactored unqiue tests into their own class
joferkington d9ea28d
TST: Added basic tests for an invalid axis kwarg to unique
joferkington File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -90,7 +90,7 @@ def ediff1d(ary, to_end=None, to_begin=None): | |
|
||
return ed | ||
|
||
def unique(ar, return_index=False, return_inverse=False): | ||
def unique(ar, return_index=False, return_inverse=False, axis=None): | ||
""" | ||
Find the unique elements of an array. | ||
|
||
|
@@ -102,13 +102,18 @@ def unique(ar, return_index=False, return_inverse=False): | |
Parameters | ||
---------- | ||
ar : array_like | ||
Input array. This will be flattened if it is not already 1-D. | ||
Input array. Unless `axis` is specified, this will be flattened if it | ||
is not already 1-D. | ||
return_index : bool, optional | ||
If True, also return the indices of `ar` that result in the unique | ||
array. | ||
If True, also return the indices of `ar` along the specified axis that | ||
result in the unique array. | ||
return_inverse : bool, optional | ||
If True, also return the indices of the unique array that can be used | ||
to reconstruct `ar`. | ||
10000 | If True, also return the indices of the unique array along the | |
specified axis that can be used to reconstruct `ar`. | ||
axis : int or None, optional | ||
The axis to operate on. If None, `ar` will be flattened beforehand. | ||
Object arrays or structured arrays that contain objects are not | ||
supported if the `axis` kwarg is used. | ||
|
||
Returns | ||
------- | ||
|
@@ -134,6 +139,12 @@ def unique(ar, return_index=False, return_inverse=False): | |
>>> np.unique(a) | ||
array([1, 2, 3]) | ||
|
||
Return the unique rows of a 2D array | ||
|
||
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) | ||
>>> np.unique(a, axis=0) | ||
array([[1, 0, 0], [2, 3, 4]]) | ||
|
||
Return the indices of the original array that give the unique values: | ||
|
||
>>> a = np.array(['a', 'b', 'b', 'c', 'a']) | ||
|
@@ -158,6 +169,47 @@ def unique(ar, return_index=False, return_inverse=False): | |
>>> u[indices] | ||
array([1, 2, 6, 4, 2, 3, 2]) | ||
|
||
""" | ||
if axis is None: | ||
return _unique1d(ar, return_index, return_inverse) | ||
if abs(axis) > ar.ndim: | ||
raise ValueError('Invalid axis kwarg specified for unique') | ||
|
||
ar = np.swapaxes(ar, axis, 0) | ||
orig_shape, orig_dtype = ar.shape, ar.dtype | ||
# Must reshape to a contiguous 2D array for this to work... | ||
ar = ar.reshape(orig_shape[0], -1) | ||
ar = np.ascontiguousarray(ar) | ||
|
||
if ar.dtype.char in (np.typecodes['AllInteger'] + 'S'): | ||
# Optimization inspired by <http://stackoverflow.com/a/16973510/325565> | ||
dtype = np.dtype((np.void, ar.dtype.itemsize * ar.shape[1])) | ||
else: | ||
dtype = [('f{i}'.format(i=i), ar.dtype) for i in range(ar.shape[1])] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure if it is worth it, but if the dtype has no fields, you probably could also use [('', ar.dtype, ar.shape[1])]. (Also could write |
||
|
||
try: | ||
consolidated = ar.view(dtype) | ||
except TypeError: | ||
# There's no good way to do this for object arrays, etc... | ||
msg = 'The axis argument to unique is not supported for dtype {dt}' | ||
raise TypeError(msg.format(dt=ar.dtype)) | ||
|
||
def reshape_uniq(uniq): | ||
uniq = uniq.view(orig_dtype) | ||
uniq = uniq.reshape(-1, *orig_shape[1:]) | ||
uniq = np.swapaxes(uniq, 0, axis) | ||
return uniq | ||
|
||
output = _unique1d(consolidated, return_index, return_inverse) | ||
if not (return_index or return_inverse): | ||
return reshape_uniq(output) | ||
else: | ||
uniq = reshape_uniq(output[0]) | ||
return tuple([uniq] + list(output[1:])) | ||
|
||
def _unique1d(ar, return_index=False, return_inverse=False): | ||
""" | ||
Find the unique elements of an array. | ||
""" | ||
try: | ||
ar = ar.flatten() | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we can say this clearer? Thinking about "along", or saying that all other axis are the elements. There was some discussion about other names for the argument, but I am not sure if there was any better idea. Axis seems fine to me though.