Pandas:从字符串计数创建直方图

26
我需要从一个包含'Low'、'Medium'或'High'值的数据框列创建一个直方图。当我尝试使用通常的df.column.hist()时,会出现以下错误。
ex3.Severity.value_counts()
Out[85]: 
Low       230
Medium     21
High       16
dtype: int64

ex3.Severity.hist()


TypeError                                 Traceback (most recent call last)
<ipython-input-86-7c7023aec2e2> in <module>()
----> 1 ex3.Severity.hist()

C:\Users\C06025A\Anaconda\lib\site-packages\pandas\tools\plotting.py in hist_series(self, by, ax, grid, xlabelsize, xrot, ylabelsize, yrot, figsize, bins, **kwds)
2570         values = self.dropna().values
2571 
->2572         ax.hist(values, bins=bins, **kwds)
2573         ax.grid(grid)
2574         axes = np.array([ax])

C:\Users\C06025A\Anaconda\lib\site-packages\matplotlib\axes\_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
5620             for xi in x:
5621                 if len(xi) > 0:
->5622                     xmin = min(xmin, xi.min())
5623                     xmax = max(xmax, xi.max())
5624             bin_range = (xmin, xmax)

TypeError: unorderable types: str() < float()

1
我猜想你的数据只是字符串,你是否想要使用 ex3.Severity.value_counts().hist() - EdChum
谢谢,你是正确的。我假设他的功能是针对字符串内置的,并且我不需要调用value_counts。 - Kyle
我应该发布为答案吗? - EdChum
4个回答

63
ex3.Severity.value_counts().plot(kind='bar')

这就是你真正想要的。

当你执行以下操作时:

ex3.Severity.value_counts().hist()

它将轴搞反了,即它试图将您的y轴(计数)分成箱子,然后绘制每个箱中字符串标签的数量。


是的,你说得对。很奇怪,这在 Pandas 中使用数字列可以正常工作,但使用文本列需要完全不同的东西。 - cardamom
在我的pandas v0.19.2版本中可以运行。 - Selah

11

只是一个更新的回答(因为这经常出现)。Pandas有一个很好的模块可以以多种方式为数据框进行样式设置,例如上面提到的情况....

ex3.Severity.value_counts().to_frame().style.bar()

...将打印具有内置条形图的数据框(作为sparklines,使用excel术语)。在jupyter笔记本上进行快速分析非常好。

请参见pandas样式文档


8

这是一个matplotlib问题,无法将字符串排序在一起,但您可以通过标记x轴刻度来实现所需的结果:

# emulate your ex3.Severity.value_counts()
data = {'Low': 2, 'Medium': 4, 'High': 5}
df = pd.Series(data)

plt.bar(range(len(df)), df.values, align='center')
plt.xticks(range(len(df)), df.index.values, size='small')
plt.show()

histogram


5
你认为由于你的数据是字符串,调用 plot() 会自动执行 value_counts(),但事实并非如此,因此出现了错误,你只需要做的是:
ex3.Severity.value_counts().hist()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接