在 Python 中使用 Counter() 构建直方图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19198920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Counter() in Python to build histogram?
提问by marc
I saw on another question that I could use Counter()
to count the number of occurrences in a set of strings. So if I have ['A','B','A','C','A','A']
I get Counter({'A':3,'B':1,'C':1})
. But now, how can I use that information to build a histogram for example?
我在另一个问题上看到,我可以用它Counter()
来计算一组字符串中出现的次数。所以如果我有['A','B','A','C','A','A']
我得到Counter({'A':3,'B':1,'C':1})
. 但是现在,例如,我如何使用该信息来构建直方图?
采纳答案by Igonato
For your data it is probably better to use a barchart instead of a histogram. Check out this code:
对于您的数据,最好使用条形图而不是直方图。看看这个代码:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
labels, values = zip(*Counter(['A','B','A','C','A','A']).items())
indexes = np.arange(len(labels))
width = 1
plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()
Result:
结果:
回答by Phillip Cloud
You can write some really concise code to do this using pandas:
您可以使用pandas编写一些非常简洁的代码来执行此操作:
In [24]: import numpy as np
In [25]: from pandas import Series
In [27]: sample = np.random.choice(['a', 'b'], size=10)
In [28]: s = Series(sample)
In [29]: s
Out[29]:
0 a
1 b
2 b
3 b
4 a
5 b
6 b
7 b
8 b
9 a
dtype: object
In [30]: vc = s.value_counts()
In [31]: vc
Out[31]:
b 7
a 3
dtype: int64
In [32]: vc = vc.sort_index()
In [33]: vc
Out[33]:
a 3
b 7
dtype: int64
In [34]: vc.plot(kind='bar')
Resulting in:
导致: