要对数据进行分组,请将其除以间隔宽度.要计算每个组中的数字,请考虑使用collections.Counter.这是一个带有文档和测试的实例:
from collections import Counter
def histogram(iterable, low, high, bins):
'''Count elements from the iterable into evenly spaced bins
>>> scores = [82, 85, 90, 91, 70, 87, 45]
>>> histogram(scores, 0, 100, 10)
[0, 0, 0, 0, 1, 0, 0, 1, 3, 2]
'''
step = (high - low + 0.0) / bins
dist = Counter((float(x) - low) // step for x in iterable)
return [dist[b] for b in range(bins)]
if __name__ == '__main__':
import doctest
print doctest.testmod()
Run Code Online (Sandbox Code Playgroud)
如果您使用外部库NumPy可以,那么您只需要调用numpy.histogram():
>>> data = [82, 85, 90, 91, 70, 87, 45]
>>> counts, bins = numpy.histogram(data, bins=10, range=(0, 100))
>>> counts
array([0, 0, 0, 0, 1, 0, 0, 1, 3, 2])
>>> bins
array([ 0., 10., 20., 30., 40., 50., 60., 70., 80.,
90., 100.])
Run Code Online (Sandbox Code Playgroud)