如何将pandas.core.series.Series绘制为条形图?

时间:2019-07-20 20:28:52

标签: python pandas

我正在尝试绘制一个pandas系列变量,该变量在第一列中具有数字ID,在下一列中具有该ID的频率。我希望将这两幅图绘制为条形图,在y轴上显示频率,id为no。在x轴上但是,行太多,即ID号。有没有办法我只能绘制出最常出现的前10个ID?

执行此代码-area_count.plot.bar 给出此错误-

<bound method SeriesPlotMethods.bar of 
<pandas.plotting._core.SeriesPlotMethods object at 0x0000019C68029908>>

我尝试使用以下代码将本系列的前20个值存储到另一个变量中:

for i in range(1,20):
    f[i,:] = area_count[i,:]

但是它显示了此错误:

ValueError                                Traceback (most recent call last)
<ipython-input-88-1020cb7bdfc3> in <module>
      1 for i in range(1,20):
----> 2     f[i,:] = area_count[i,:]

~\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    909             key = check_bool_indexer(self.index, key)
    910 
--> 911         return self._get_with(key)
    912 
    913     def _get_with(self, key):

~\Anaconda3\lib\site-packages\pandas\core\series.py in _get_with(self, key)
    921         elif isinstance(key, tuple):
    922             try:
--> 923                 return self._get_values_tuple(key)
    924             except Exception:
    925                 if len(key) == 1:

~\Anaconda3\lib\site-packages\pandas\core\series.py in _get_values_tuple(self, key)
    966 
    967         if not isinstance(self.index, MultiIndex):
--> 968             raise ValueError('Can only tuple-index with a MultiIndex')
    969 
    970         # If key is contained, would have returned by now

ValueError: Can only tuple-index with a MultiIndex

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您现在需要使用前10个经常出现的ID,可以通过将系列转化为像这样的数据框来实现:

x = df['id'].value_counts().sort_values(ascending = False).head(10).to_frame().reset_index()
x.rename(columns = {'index':'id', 'id': 'freq'}, inplace = True)

现在绘制图形:

x.plot.bar(x = 'id', y = 'freq')

样本输出:

enter image description here