Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get frequency count of elements in an array

Tags:

python

Hi I have a list of values. I want to get another list with the amount of times every values in that list occurs. This is fairly easy, but I also need to have the values which are not present in the original list, to be present in the frequency list, but then with value 0. For example:

I = [0,1,1,2,2,2,4,4,5,5,6,6,6,8,8,8]

What you expect:

freqI = [1,2,3,2,2,2,3,3]

What I need:

freqI = [1,2,3,0,2,2,3,0,3]

As you can see 3 and 7 are not present in I, though they are still accounted for in the frequency list.

My initial try ended up giving me the first kind of solution (with the intermediate values):

d = {x:I.count(x) for x in I}

sorted_x = sorted(d.iteritems(), key=operator.itemgetter(0))

How can I get the frequency count (aka histogram) of my array, with the intermediate values present ?

like image 424
Olivier_s_j Avatar asked Dec 02 '22 19:12

Olivier_s_j


2 Answers

>>> lis = [0,1,1,2,2,2,4,4,5,5,6,6,6,8,8,8]
>>> maxx,minn = max(lis),min(lis)
>>> from collections import Counter
>>> c = Counter(lis)
>>> [c[i] for i in xrange(minn,maxx+1)]
[1, 2, 3, 0, 2, 2, 3, 0, 3]

or as suggested by @DSM we can get min and max from the dict itself:

>>> [c[i] for i in xrange( min(c) , max(c)+1)]
[1, 2, 3, 0, 2, 2, 3, 0, 3]
like image 155
Ashwini Chaudhary Avatar answered Dec 15 '22 05:12

Ashwini Chaudhary


How about

>>> I = [0,1,1,2,2,2,4,4,5,5,6,6,6,8,8,8]
>>> from collections import Counter
>>> frequencies = Counter(I)
>>> frequencies
Counter({2: 3, 6: 3, 8: 3, 1: 2, 4: 2, 5: 2, 0: 1})

You can query the counter for any number. For numbers it hasn't seen, it gives 0

>>> frequencies[42]
0
like image 44
Colonel Panic Avatar answered Dec 15 '22 04:12

Colonel Panic