numpy/numpy — pull request #3584 by joferkington (2013-08-07 11:51:31+00:00)
Title: ENH: Add an ``axis`` kwarg to ``numpy.unique``

Description
----------------
Adds an ``axis`` kwarg to ``numpy.unique`` so that ``unique`` can easily be used to find unique rows/columns/sub-arrays/etc of a larger ndarray.

Rationale
-------------
There is often a need to find unique rows/columns/etc of an array. However, ``numpy.unique`` currently operates only on the flattened array, and returns unique elements. It is possible to work around this in several ways (e.g. viewing each row/column/etc as a structured array or a void dtype the size of the row/column in question). However, each of these work-arounds requires a fairly in-depth knowledge of numpy. Having an ``axis`` kwarg to ``unique`` makes this operation much simpler.

Examples
--------------

In [1]: import numpy as np

In [2]: a = np.array([[1, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0]])

In [3]: a
Out[3]:
array([[1, 0, 1],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]])

In [4]: np.unique(a)
Out[4]: array([0, 1])

In [5]: np.unique(a, axis=0)
Out[5]:
array([[0, 1, 0],
[1, 0, 1]])

In [6]: np.unique(a, axis=1)
Out[6]:
array([[0, 1],
[1, 0],
[1, 0],
[1, 0]])

In [7]: b = np.dstack([a]*3).T

In [8]: b
Out[8]:
array([[[1, 0, 0, 0],
[0, 1, 1, 1],
[1, 0, 0, 0]],

[[1, 0, 0, 0],
[0, 1, 1, 1],
[1, 0, 0, 0]],

[[1, 0, 0, 0],
[0, 1, 1, 1],
[1, 0, 0, 0]]])

In [9]: np.unique(b, axis=0)
Out[9]:
array([[[1, 0, 0, 0],
[0, 1, 1, 1],
[1, 0, 0, 0]]])