Created
June 1, 2015 13:24
-
-
Save aphearin/e7e1ac21428ddfcf12bf to your computer and use it in GitHub Desktop.
Method to retrieve the array elements that fall within a bin.
This file contains 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
def binned_elements_finder(x, bin_limits): | |
""" Given an array x, and a set of bin limits on x, | |
return an indexer and a set of slices for retrieiving the set of points | |
in x that lie in the i^th bin. | |
Parameters | |
---------- | |
x : array | |
bin_limits : array | |
Returns | |
------- | |
x_sorted : array | |
The input array x after sorting on the bin indices | |
slices : array | |
List of slice objects. The i^th array element is a slice object that | |
allows you to access the points in x that fall in the i^th bin. | |
Examples | |
-------- | |
>>> x = np.logspace(-1, 1, 1e6) | |
>>> bin_limits = np.linspace(0, 10, 5) | |
>>> x_sorted, slices = binned_elements_finder(x, bin_limits) | |
The elements of x that reside in the i^th bin can be accessed as follows: | |
>>> x_bini = x_sorted[slices[i]] | |
""" | |
indexsort = np.argsort(x) | |
boundary_pts = np.searchsorted(x, bin_limits, sorter=indexsort) | |
slices = [slice(boundary_pts[i], boundary_pts[i+1]) for i in range(len(boundary_pts)-1)] | |
return (x[indexsort], slices) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment