1

I'm trying to categorize numbers into "bins" so if a bin is all numbers in the range 0 to 20, then 19 falls into that bin.

I'm trying to do this without using a bunch of if-then states like so:

if x < 0.5:
    return "bin1"
elif x < 0.8:
    return "bin2"
...

Numpy has a numpy.linspace method that generates a numpy array with evenly spaced bins. However, I still don't see how to do this bin categorization efficiently without taking the results of the array and putting them in "if" statements. Thanks.

1
  • Are your bins contiguous and do they all have the same width? Commented Nov 30, 2013 at 21:02

2 Answers 2

6
import bisect

bins = range(0, 100, 15)

print bisect.bisect_left(bins, 35)
Sign up to request clarification or add additional context in comments.

Comments

3

You can use numpy.searchsorted:

>>> import numpy as np    

>>> bins = np.array([0, 10, 100, 1000])
>>> numbers = np.array([800, 8, 80])
>>> print bins.searchsorted(numbers)
[3, 1, 2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.