vectorized approach to binning with numpy/scipy in Python

Posted by user248237 on Stack Overflow See other posts from Stack Overflow or by user248237
Published on 2010-05-02T20:46:24Z Indexed on 2010/05/03 9:28 UTC
Read the original article Hit count: 326

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about numpy