【问题标题】:Pandas / pyplot histogram: can plot df but not subsetPandas / pyplot histogram:可以绘制df但不能绘制子集
【发布时间】:2016-02-27 06:54:15
【问题描述】:

df 是一个巨大的数据框。我只需要 Zcoord > 1 的子集。

df = pandas.DataFrame(first)
df.columns = ['Xcoord', 'Ycoord', 'Zcoord', 'Angle']
df0 = df[df.Zcoord>1]

绘制 df 直方图的相同代码不适用于 df0。

plot1 = plt.figure(1)
plt.hist(df0.Zcoord, bins=100, normed=False)
plt.show()

Ipython 吐出 KeyError:0。

python 2.7.9 anaconda、ipython 2.2.0、OS 10.9.4

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-42-71643df3888f> in <module>()
      1 plot1 = plt.figure(1)
----> 2 plt.hist(df0.Zcoord, bins=100, normed=False)
      3 
      4 plt.show()
      5 from matplotlib.backends.backend_pdf import PdfPages

/Users/Kit/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, **kwargs)
   2888                       histtype=histtype, align=align, orientation=orientation,
   2889                       rwidth=rwidth, log=log, color=color, label=label,
-> 2890                       stacked=stacked, **kwargs)
   2891         draw_if_interactive()
   2892     finally:

/Users/Kit/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
   5560         # Massage 'x' for processing.
   5561         # NOTE: Be sure any changes here is also done below to 'weights'
-> 5562         if isinstance(x, np.ndarray) or not iterable(x[0]):
   5563             # TODO: support masked arrays;
   5564             x = np.asarray(x)

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
    482     def __getitem__(self, key):
    483         try:
--> 484             result = self.index.get_value(self, key)
    485 
    486             if not np.isscalar(result):

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
   1194 
   1195         try:
-> 1196             return self._engine.get_value(s, k)
   1197         except KeyError as e1:
   1198             if len(self) > 0 and self.inferred_type in ['integer','boolean']:

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/index.so in pandas.index.IndexEngine.get_value (pandas/index.c:2993)()

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/index.so in pandas.index.IndexEngine.get_value (pandas/index.c:2808)()

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/index.so in pandas.index.IndexEngine.get_loc (pandas/index.c:3440)()

KeyError: 0

【问题讨论】:

    标签: python python-2.7 pandas matplotlib ipython-notebook


    【解决方案1】:

    您将 pandas.Series 传递给 matplotlib (df0.Zcoord)。然而,目前,matplotlib 对于它是否喜欢被提供 pandas 数据类型(而不是 numpy ndarray's)有点犹豫不决。

    在 matplotlib 源代码内部的某个时刻,直方图函数可能试图获取“我被要求处理的第一个项目”,它可能通过调用 input[0] where @ 987654326@ 是它被要求咀嚼的任何东西。如果inputnumpy.ndarray,那么一切正常。然而,如果inputpandas.Series 或者(甚至更糟)pandas.DataFrame,则表达式input[0] 将具有非常不同的含义。在这种情况下,根据您提供给plt.hist 的数据结构,在尝试对您的输入进行索引时很可能会有KeyError

    在您的特定情况下,这可能在整个 df 上运行良好,因为 df 可能有一个整数索引 ([0, 1, 2, ..., len(df)-1]),这是 DataFrame 中的默认行索引。但是,当您在df 中选择以生成df0 时,结果会以一个索引结束,该索引是df 的索引的子集(可能以[3, 6, 9, 12, ...] 结束)。所以在df(索引包含0)上一切正常,但在df0(具有讽刺意味的是,鉴于其名称,0 没有出现在索引中)。

    快速修复...而不是

    plt.hist(df0.Zcoord, bins=100, normed=False)
    

    运行这个

    plt.hist(df0.Zcoord.values, bins=100, normed=False)
    

    我猜一切都会好的。

    【讨论】:

    • 很高兴它有帮助!如果您有兴趣,here 是讨论此问题的线程。如果您可以在原始帖子中包含更多的堆栈跟踪,那就太好了,这样其他人就可以准确地看到错误来自哪里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2021-08-27
    • 1970-01-01
    • 2021-03-23
    • 2021-06-13
    • 2016-05-25
    相关资源
    最近更新 更多