Question: I am binning a 2d array (x by y) in Python into the bins of its x value (given in "bins"), using np.digitize:

```
elements_to_bins = digitize(vals, bins)

```

where "vals" is a 2d array, i.e.:

```
 vals = array([[1, v1], [2, v2], ...]). 

```

elements\_to\_bins just says what bin each element falls into. What I then want to do is get a list whose length is the number of bins in "bins", and each element returns the y-dimension of "vals" that falls into that bin. I do it this way right now:

```
points_by_bins = []
for curr_bin in range(min(elements_to_bins), max(elements_to_bins) + 1):
    curr_indx = where(elements_to_bins == curr_bin)[0]
    curr_bin_vals = vals[:, curr_indx]
    points_by_bins.append(curr_bin_vals)

```

is there a more elegant/simpler way to do this? All I need is a list of of lists of the y-values that fall into each bin.

thanks.

Answer: 
This will return a data structure analogous to IDL HISTOGRAM's Reverse\_Indices:

```
ovec = np.argsort(vals)
ivec = np.searchsorted(vals, bin_limits, sorter=ovec)

```

Then the list of elements that fall into bin #i is

```
ovec[ ivec[i] : ivec[i+1] ]

```

(my quick timing tests say this is 5x faster than EOL's algorithm, since it doesn't bother creating different-sized lists)
Are the bin keys just integers, no binning, as in your example ? Then you could just do this, without numpy:

```
from collections import defaultdict
bins = defaultdict(list)  # or [ [] ...] as in EOL

vals = [[1, 10], [1, 11], [2, 20], [2, 21], [2, 22]]  # nparray.tolist()
for nbin, val in vals:
    bins[nbin].append(val)

print "bins:", bins
# defaultdict(<type 'list'>, {1: [10, 11], 2: [20, 21, 22]})

```