0

I have a set of values as :-

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

Now, how can i bin them into groups such that the decimal values will go to the nearest integer value and give the no of its occurrence. ie.,say if value is 1.2 it should go to 1.0 and if value is 8.6 it should go to 9 (its nearest integer).

and i want the output as:-

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

and hence i can get the bins as x axis and its no.of times of occurrence on y axis and hence plot the graph. How can i write a python program for this..??

D.H.N
  • 69
  • 1
  • 9

2 Answers2

1
from collections import Counter

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

alternatively (if numpy is available),

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)

then for display,

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

gives

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
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • But how can i get it in this form 1.0 4 2.0 1 3.0 6 4.0 2 and so on...... ie., removing the semicolon and commas..... – D.H.N May 26 '17 at 03:34
0

Assuming that input numbers are a list we can do the following:

from collections import Counter

count_numbers=dict(Counter([round(x) for x in list_numbers]))

your result would be

{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}