<div dir="ltr"><br><div class="gmail_extra"><br><br><div class="gmail_quote">On Tue, Aug 12, 2014 at 11:35 AM, Warren Weckesser <span dir="ltr"><<a href="mailto:warren.weckesser@gmail.com" target="_blank">warren.weckesser@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr">I created a pull request (<a href="https://github.com/numpy/numpy/pull/4958" target="_blank">https://github.com/numpy/numpy/pull/4958</a>) that defines the function `count_unique`.  `count_unique` generates a contingency table from a collection of sequences.  For example,<br>

<br><span style="font-family:courier new,monospace">In [7]: x = [1, 1, 1, 1, 2, 2, 2, 2, 2]<br><br>In [8]: y = [3, 4, 3, 3, 3, 4, 5, 5, 5]<br><br>In [9]: (xvals, yvals), counts = count_unique(x, y)<br><br>In [10]: xvals<br>

Out[10]: array([1, 2])<br><br>In [11]: yvals<br>Out[11]: array([3, 4, 5])<br><br>In [12]: counts<br>Out[12]: <br>array([[3, 1, 0],<br>       [1, 1, 3]])</span><br><br><br>It can be interpreted as a multi-argument generalization of `np.unique(x, return_counts=True)`.<br>

<br>It overlaps with Pandas' `crosstab`, but I think this is a pretty fundamental counting operation that fits in numpy.<br><br>Matlab's `crosstab` (<a href="http://www.mathworks.com/help/stats/crosstab.html" target="_blank">http://www.mathworks.com/help/stats/crosstab.html</a>) and R's `table` perform the same calculation (with a few more bells and whistles).<br>

<br><br>For comparison, here's Pandas' `crosstab` (same `x` and `y` as above):<br><br><span style="font-family:courier new,monospace">In [28]: import pandas as pd<br><br>In [29]: xs = pd.Series(x)<br><br>In [30]: ys = pd.Series(y)<br>

<br>In [31]: pd.crosstab(xs, ys)<br>Out[31]: <br>col_0  3  4  5<br>row_0         <br>1      3  1  0<br>2      1  1  3</span><br><br><br>And here is R's `table`:<br><br><span style="font-family:courier new,monospace">> x <- c(1,1,1,1,2,2,2,2,2)<br>

> y <- c(3,4,3,3,3,4,5,5,5)<br>> table(x, y)<br>   y<br>x   3 4 5<br>  1 3 1 0<br>  2 1 1 3</span><br><br><br>Is there any interest in adding this (or some variation of it) to numpy?<span class=""><font color="#888888"><br>
<br><br>Warren<br><br></font></span></div>
</blockquote></div><br><br></div><div class="gmail_extra">While searching StackOverflow in the numpy tag for "count unique", I just discovered that I basically reinvented Eelco Hoogendoorn's code in his answer to <a href="http://stackoverflow.com/questions/10741346/numpy-frequency-counts-for-unique-values-in-an-array">http://stackoverflow.com/questions/10741346/numpy-frequency-counts-for-unique-values-in-an-array</a>.  Nice one, Eelco!<br>
<br></div><div class="gmail_extra">Warren<br><br></div></div>