Python binning frequency distribution

I have data in two lists of value and frequency like this:

  value freq
 12
 2 1
 3 3
 6 2
 7 3
 8 3
 ....

and I want the result to be

  bin freq
 1-3 6
 4-6 2
 7-9 6
 ...

I can write a few lines of code to do this. However, I am looking to see if there are builitin functions in standard python or Numpy? I found a solution when you are given data in an array / list with repetition, i.e. They have not yet been grouped into a frequency table (for example, d= [1,1,2,3,3,3,6,6,7,7,7,8,8,8,...] . However, in this case I couldn’t find the answers.I don’t want to convert mine first enter the data in one extended list, for example d , and use the histogram function.

+4
source share
3 answers
 import numpy as np values = [1,2,3,6,7,8] freqs = [2,1,3,2,3,3] hist, _ = np.histogram(values, bins=[1, 4, 7, 10], weights=freqs) print hist 

output:

 [6 2 6] 
+9
source

you can try the following:

 import collections d=[1,1,2,3,3,3,6,6,7,7,7,8,8,8] collections.Counter([ii%3+3 for i in d]) 

it will generate a dictionary with what you want.

0
source

I found a solution when you are given data in an array / list with repetition

You did not say what the solution is, but if it supports iterator reception, you can generate it instead of creating the whole list:

import itertools

 values = [1,2,3,6] freqs = [2,1,3,2] v_iter = itertools.chain(*[ itertools.repeat(v,f) for v, f in zip(values, freqs) ]) #for x in v_iter: # print x your_solution(v_iter) 
0
source

All Articles