如何从Python中的字符串列表制作直方图? [英] How to make a histogram from a list of strings in Python?

查看:234
本文介绍了如何从Python中的字符串列表制作直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']

我想制作一个直方图来显示字母的频率分布.我可以使用以下代码制作一个包含每个字母的计数的列表:

I want to make a histogram for displaying the frequency distribution of the letters. I can make a list that contains the count of each letter using following codes:

from itertools import groupby
b = [len(list(group)) for key, group in groupby(a)]

如何制作直方图?我可能在列表a中有一百万个这样的元素.

How do I make the histogram? I may have a million such elements in list a.

推荐答案

使用Pandas非常容易.

import pandas
from collections import Counter
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
letter_counts = Counter(a)
df = pandas.DataFrame.from_dict(letter_counts, orient='index')
df.plot(kind='bar')

请注意,Counter在进行频率计数,因此我们的绘图类型是'bar'而不是'hist'.

Notice that Counter is making a frequency count, so our plot type is 'bar' not 'hist'.

这篇关于如何从Python中的字符串列表制作直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆