Pythonic way to classify a value to bin

Viewed 55

I've went through multiple excamples of data classification however either I didn't get it or those are not applicable in my case.

I have a list of values:

values = [-130,-110,-90,-80,-60,-40]

All I need to do is to classify input integer value to appropriate "bin".

E.g., input=-97 should get index 1 (between -110, to -90) , while input=-140 should get 0.

I don't want to do it if...elif else style since values could be dynamic.

What would be the most pythonic way to do it? I guess no pandas/numpy is necessary

Regards

2 Answers

You can traverse the list of bins and find the index of the first ([0]) bin boundary that is bigger than the classified value. Then step back to the previous bin number:

val = -97
[i for i,p in enumerate(values) if p > val][0] - 1
# 1

This solution works only for values[0] <= val < values[-1].

Solution with embedded module - bisect.

bisect_left(a, x) return the index to insert into the list a to the left of values greater x than the input. Check index into sotrted list.

If my interpretation of your question is right code like this.

from bisect import bisect_left
values = [-130,-110,-90,-80,-60,-40]

i = bisect_left(values, -97)
if i > 0:
    i -= 1
Related