hassan
hassan

Reputation: 133

Calculate the percentage for python dictionary

I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with d=(Counter([Counter(i)['1'] for i in f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()

Upvotes: 0

Views: 10550

Answers (4)

e.s.
e.s.

Reputation: 1371

you can use list comp.

In[2]: my_dict = {key: key for key in range(5)}
In[3]: values = my_dict.values()
In[4]: values
Out[4]: [0, 1, 2, 3, 4]
In[5]: total = sum(values)
In[6]: new = [value * 100. / total for value in values]
In[7]: new
Out[7]: [0.0, 10.0, 20.0, 30.0, 40.0]

or you can use np.array

In[8]: import numpy as np
In[9]: x = np.array([1, 2, 3, 4])
In[10]: x
Out[10]: array([1, 2, 3, 4])
In[11]: x/3.4
Out[11]: array([ 0.29411765,  0.58823529,  0.88235294,  1.17647059])

Upvotes: 0

Paul Cornelius
Paul Cornelius

Reputation: 10946

For any dictionary d, whose values are integers, the percentage of the total represented by each item can be calculated and printed as follows:

s = sum(d.values())
for k, v in d.items():
    pct = v * 100.0 / s
    print(k, pct)

numpy is overkill for this, and it's optimized for arrays rather than dictionaries.

Upvotes: 2

Rohan
Rohan

Reputation: 5431

Use numpy

x = np.array(d.values())
print x*100.0/sum(x)

Upvotes: -1

Abid Hasan
Abid Hasan

Reputation: 658

You probably want to use len(d.values()) to get the number of items, unless I'm missing something. Can you please share what the dictionary (d) looks like? (i.e. the output of print d?)

Upvotes: 0

Related Questions