熊猫:根据字符串计数创建直方图

Kyl*_*yle 11 pandas

我需要从包含值"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()
Run Code Online (Sandbox Code Playgroud)

小智 27

ex3.Severity.value_counts().plot(kind='bar')
Run Code Online (Sandbox Code Playgroud)

是你真正想要的.

当你这样做时:

ex3.Severity.value_counts().hist()
Run Code Online (Sandbox Code Playgroud)

它使得轴绕错了方向,即它试图将你的y轴(计数)分割成箱子,然后绘制每个箱子中的字符串标签数量.


Ouy*_* Ze 9

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

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

...将打印带有内置条的数据框(作为迷你图,使用 excel 术语)。非常适合对 jupyter 笔记本进行快速分析。

查看熊猫造型文档


Kik*_*ohs 8

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

# 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()
Run Code Online (Sandbox Code Playgroud)

直方图


EdC*_*ica 5

你假设因为你的数据由字符串组成,调用plot()它会自动执行,value_counts()但事实并非如此,所以你需要做的就是:

ex3.Severity.value_counts().hist()
Run Code Online (Sandbox Code Playgroud)