将值分类到 bin 的 Pythonic 方法
我已经经历了多个数据分类示例,但是要么我没有得到它,要么这些示例不适用于我的情况。
我有一个值列表:
values = [-130,-110,-90,-80,-60,-40]
我需要做的就是将输入整数值分类到适当的“bin”。
例如, input=-97
应该得到 index 1
(在 -110 到 -90 之间),而 input=-140
应该得到 0。
我不想这样做 if...elif else style
因为值可能是动态的。
最Pythonic的方法是什么?我想不需要 pandas/numpy
问候
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用嵌入式模块的解决方案 -
二等
。bisect_left(a,x)
将索引返回列表a
的索引,比输入更大的x
。将索引纳入索引列表。如果我对您的问题的解释是正确的代码。
Solution with embedded module -
bisect
.bisect_left(a, x)
return the index to insert into the lista
to the left of values greaterx
than the input. Check index into sotrted list.If my interpretation of your question is right code like this.
您可以遍历 bin 列表并找到大于分类值的第一个 (
[0]
) bin 边界的索引。然后返回到之前的 bin 编号:此解决方案仅适用于
values[0] <= val <值[-1]
。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:This solution works only for
values[0] <= val < values[-1]
.