关于python中值的Binning

时间:2017-05-25 17:14:24

标签: python integer decimal bins

我有一组值为: -

1.2 
1.0 
2.6 
2.4 
2.8 
5.1 
2.5 
5.4 
1.3 
1.1 
10.3 
4.1 
3.4 
3.2 
6.1 
6.3 
9.0 
8.6 
7.1 
3.2 
4.3 
15.0 
12.3 
13.1 
17.4 
10.2 
11.7 
14.6 
16.3

现在,我如何将它们分组成小组,使得十进制值将转到最接近的整数值,并给出它的出现次数。即,如果值为1.2,则应该为1.0,如果值为8.6,则应为9(最接近的整数)。

我希望输出为: -

0.0 - 1.0    its occurrence
1.1 - 2.0    its occurrence
2.1 - 3.0    its occurrence
3.1 - 4.0    its occurrence
4.1 - 5.0    its occurrence
16.1 - 17.0  its occurrence

因此我可以将箱子作为x轴及其在y轴上出现的次数,从而绘制图表。 我怎么能为此编写一个python程序.. ??

2 个答案:

答案 0 :(得分:1)

from collections import Counter

c = Counter(round(f) for f in values)

或者(如果numpy可用),

import numpy as np

minval = int(min(values))
maxval = int(max(values)) + 1.
bins = np.arange(minval, maxval + 1, 1.)
hist, edges = np.histogram(values, bins)

然后显示,

for lo, hi, num in zip(edges, edges[1:], hist):
    print("{} - {}: {}".format(lo, hi, num))

给出

1.0 - 2.0: 4
2.0 - 3.0: 4
3.0 - 4.0: 3
4.0 - 5.0: 2
5.0 - 6.0: 2
6.0 - 7.0: 2
7.0 - 8.0: 1
8.0 - 9.0: 1
9.0 - 10.0: 1
10.0 - 11.0: 2
11.0 - 12.0: 1
12.0 - 13.0: 1
13.0 - 14.0: 1
14.0 - 15.0: 1
15.0 - 16.0: 1
16.0 - 17.0: 1
17.0 - 18.0: 1

答案 1 :(得分:0)

假设输入数字是一个列表,我们可以执行以下操作:

来自集合导入计数器

count_numbers = dict(计数器(list_numbers中x的[round(x)]))

你的结果将是

{1.0:4,2.0:1,3.0:6,4.0:2,5.0:2,6.0:2,7.0:1,9.0:2,10.0:2,12.0:2,13.0:1,15.0: 2,16.0:1,17.0:1}