简体   繁体   English

计算Python字典的百分比

[英]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. d.values/sum(d.values)*100它给出错误:/的unsupported operand type(s) for /: 'list' and 'int'您无法将整个列表除以任何整数。 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. 我认为,在=(Counter([Counter(i)['1'] for i in f.readlines()]))我尝试使用d =(Counter([Counter(i)['1'] for i in f.readlines()])) ,您可以计算百分比,但是没有用。 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()

You probably want to use len(d.values()) to get the number of items, unless I'm missing something. 您可能要使用len(d.values())来获取项目数,除非我遗漏了一些东西。 Can you please share what the dictionary (d) looks like? 您能分享一下字典(d)的样子吗? (ie the output of print d?) (即输出d的输出?)

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 或者你可以使用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])

For any dictionary d, whose values are integers, the percentage of the total represented by each item can be calculated and printed as follows: 对于任何值为整数的字典d,可以按以下方式计算和打印每个项目所代表的总数的百分比:

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. numpy对此过于矫kill过正,并且针对数组而不是字典进行了优化。

Use numpy 使用numpy

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM