[英]Digitizing value to “floor” bin python
我需要数字化一些值,以使返回的索引是“ floor”或“ ceiling” bin。
例如,对于bins = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])
和值0.2
我期望索引为0
,对于值0.26
,返回的索引应为1
,依此类推。
我有以下看起来很丑陋的功能来做我想做的事情:
import numpy
def get_bin_index(value, bins):
bin_diff = bins[1]-bins[0]
index = numpy.digitize(value, bins)
if bins[index] - value > bin_diff/2.0:
index -= 1
return index
是否有任何简洁(更好/有效的阅读方法)来做到这一点?
编辑:包括时间值(仅满足我的好奇心!)
In [1]: def get_bin_index(value, bins):
...: bin_diff = bins[1]-bins[0]
...: index = numpy.digitize(value, bins)
...: if bins[index] - value > bin_diff/2.0:
...: index -= 1
...: return index
...:
In [2]: def get_bin_index_c(value, bins):
...: return numpy.rint((value-bins[0])/(bins[1]-bins[0]))
...:
In [3]: def get_bin_index_mid_digitized(value, bins):
...: return numpy.digitize(0.6, (bins[1:] + bins[:-1])/2.0)
...:
In [4]: bin_halfs = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])
In [5]: %timeit get_bin_index(0.9, bin_halfs)
The slowest run took 5.71 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 4.93 µs per loop
In [6]: %timeit get_bin_index_c(0.9, bin_halfs)
The slowest run took 14.60 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.34 µs per loop
In [7]: %timeit get_bin_index_mid_digitized(0.9, bin_halfs)
The slowest run took 4.09 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 8.37 µs per loop
您可以简单地获取垃圾箱的中间位置,并与np.digitize
使用-
np.digitize(value, (bins[1:] + bins[:-1])/2.0)
如果bin_diffs都相同,则可以通过以下方式在恒定时间内执行此操作:
def get_bin_index2(value, bins):
return numpy.rint((value - bins[0])/(bins[1]-bins[0]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.