将值分类到 bin 的 Pythonic 方法

发布于 2025-01-17 09:00:03 字数 382 浏览 3 评论 0原文

我已经经历了多个数据分类示例,但是要么我没有得到它,要么这些示例不适用于我的情况。

我有一个值列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奢望 2025-01-24 09:00:03

使用嵌入式模块的解决方案 - 二等

bisect_left(a,x)将索引返回列表a的索引,比输入更大的x。将索引纳入索引列表。

如果我对您的问题的解释是正确的代码。

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

i = bisect_left(values, -97)
if i > 0:
    i -= 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
夏の忆 2025-01-24 09:00:03

您可以遍历 bin 列表并找到大于分类值的第一个 ([0]) bin 边界的索引。然后返回到之前的 bin 编号:

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

此解决方案仅适用于 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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文