1

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

morf
  • 125
  • 11
  • 1
    Do all "bins" have the same width? Are they consecutive? Are the input values always integers, or can they be arbitrary floats? – Brian61354270 Mar 28 '22 at 14:27

2 Answers2

2

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].

DYZ
  • 55,249
  • 10
  • 64
  • 93
2

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
Eugene
  • 345
  • 1
  • 7