freq function

Dirk Nachbar dirknbr at gmail.com
Sun Aug 22 04:01:55 EDT 2010


Here is a function which takes any list and creates a freq table,
which can be printed unsorted, sorted by cases or items. It's supposed
to mirror the proc freq in SAS.

Dirk

def freq(seq,order='unsorted',prin=True):
    #order can be unsorted, cases, items

    freq={}
    for s in seq:
        if s in freq:
            freq[s]+=1
        else:
            freq[s]=1
    if prin==True:
        print 'Items=',len(seq),'Cases=',len(freq)
        print '------------------------'
        if order=='unsorted':
            for k in freq.keys():
                print k,freq[k],float(freq[k])/len(seq)
        elif order=='cases':
            #http://blog.client9.com/2007/11/sorting-python-dict-by-
value.html
            freq2=sorted(freq.iteritems(), key=lambda (k,v):
(v,k),reverse=True)
            for f in freq2:
                print f[0],f[1],float(f[1])/len(seq)
        elif order=='items':
            for k in sorted(freq.iterkeys()):
                print k,freq[k],float(freq[k])/len(seq)
        print '------------------------'
    return freq

#test

import random

rand=[]
for i in range(10000):
    rand.append(str(int(100*random.random())))

fr=freq(rand)
fr2=freq(rand,order='items')
fr2=freq(rand,order='cases')



More information about the Python-list mailing list