使用日期时间绘制切片的 Pandas 数据框时出现 KeyError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12406162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:25:13  来源:igfitidea点击:

KeyError when plotting a sliced pandas dataframe with datetimes

pythonpandasnumpymatplotlib

提问by joris

I get a KeyError when I try to plot a slice of a pandas DataFrame column with datetimes in it. Does anybody know what could cause this?

当我尝试绘制包含日期时间的 Pandas DataFrame 列的切片时,出现 KeyError 错误。有谁知道这可能导致什么?

I managed to reproduce the error in a little self contained example (which you can also view here: http://nbviewer.ipython.org/3714142/):

我设法在一个小的自包含示例中重现了错误(您也可以在此处查看:http: //nbviewer.ipython.org/3714142/):

import numpy as np
from pandas import DataFrame
import datetime
from pylab import *

test = DataFrame({'x' : [datetime.datetime(2012,9,10) + datetime.timedelta(n) for n in range(10)], 
                  'y' : range(10)})

Now if I plot:

现在,如果我绘制:

plot(test['x'][0:5])

there is not problem, but when I plot:

没有问题,但是当我绘制时:

plot(test['x'][5:10])

I get the KeyError below (and the error message is not very helpfull to me). This only happens with datetimecolumns, not with other columns (as far as I experienced). E.g. plot(test['y'][5:10])is not a problem.

我得到下面的 KeyError (错误消息对我不是很有帮助)。这仅发生日期时间列,不能与其他列(据我所经历)。例如plot(test['y'][5:10])不是问题。

Ther error message:

错误信息:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-7-aa076e3fc4e0> in <module>()
----> 1 plot(test['x'][5:10])

C:\Python27\lib\site-packages\matplotlib\pyplot.pyc in plot(*args, **kwargs)
   2456         ax.hold(hold)
   2457     try:
-> 2458         ret = ax.plot(*args, **kwargs)
   2459         draw_if_interactive()
   2460     finally:

C:\Python27\lib\site-packages\matplotlib\axes.pyc in plot(self, *args, **kwargs)
   3846         lines = []
   3847 
-> 3848         for line in self._get_lines(*args, **kwargs):
   3849             self.add_line(line)
   3850             lines.append(line)

C:\Python27\lib\site-packages\matplotlib\axes.pyc in _grab_next_args(self, *args, **kwargs)
    321                 return
    322             if len(remaining) <= 3:
--> 323                 for seg in self._plot_args(remaining, kwargs):
    324                     yield seg
    325                 return

C:\Python27\lib\site-packages\matplotlib\axes.pyc in _plot_args(self, tup, kwargs)
    298             x = np.arange(y.shape[0], dtype=float)
    299 
--> 300         x, y = self._xy_from_xy(x, y)
    301 
    302         if self.command == 'plot':

C:\Python27\lib\site-packages\matplotlib\axes.pyc in _xy_from_xy(self, x, y)
    215         if self.axes.xaxis is not None and self.axes.yaxis is not None:
    216             bx = self.axes.xaxis.update_units(x)
--> 217             by = self.axes.yaxis.update_units(y)
    218 
    219             if self.command!='plot':

C:\Python27\lib\site-packages\matplotlib\axis.pyc in update_units(self, data)
   1277         neednew = self.converter!=converter
   1278         self.converter = converter
-> 1279         default = self.converter.default_units(data, self)
   1280         #print 'update units: default=%s, units=%s'%(default, self.units)
   1281         if default is not None and self.units is None:

C:\Python27\lib\site-packages\matplotlib\dates.pyc in default_units(x, axis)
   1153         'Return the tzinfo instance of *x* or of its first element, or None'
   1154         try:
-> 1155             x = x[0]
   1156         except (TypeError, IndexError):
   1157             pass

C:\Python27\lib\site-packages\pandas\core\series.pyc in __getitem__(self, key)
    374     def __getitem__(self, key):
    375         try:
--> 376             return self.index.get_value(self, key)
    377         except InvalidIndexError:
    378             pass

C:\Python27\lib\site-packages\pandas\core\index.pyc in get_value(self, series, key)
    529         """
    530         try:
--> 531             return self._engine.get_value(series, key)
    532         except KeyError, e1:
    533             if len(self) > 0 and self.inferred_type == 'integer':

C:\Python27\lib\site-packages\pandas\_engines.pyd in pandas._engines.IndexEngine.get_value (pandas\src\engines.c:1479)()

C:\Python27\lib\site-packages\pandas\_engines.pyd in pandas._engines.IndexEngine.get_value (pandas\src\engines.c:1374)()

C:\Python27\lib\site-packages\pandas\_engines.pyd in pandas._engines.DictIndexEngine.get_loc (pandas\src\engines.c:2498)()

C:\Python27\lib\site-packages\pandas\_engines.pyd in pandas._engines.DictIndexEngine.get_loc (pandas\src\engines.c:2460)()

KeyError: 0

采纳答案by Wouter Overmeire

HYRY explained why you get the KeyError. To plot with slices using matplotlib you can do:

HYRY 解释了您收到 KeyError 的原因。要使用 matplotlib 绘制切片,您可以执行以下操作:

In [157]: plot(test['x'][5:10].values)
Out[157]: [<matplotlib.lines.Line2D at 0xc38348c>]

In [158]: plot(test['x'][5:10].reset_index(drop=True))
Out[158]: [<matplotlib.lines.Line2D at 0xc37e3cc>]

x, y plotting in one go with 0.7.3

x, y 与 0.7.3 一起绘制

In [161]: test[5:10].set_index('x')['y'].plot()
Out[161]: <matplotlib.axes.AxesSubplot at 0xc48b1cc>

回答by HYRY

Instead of calling plot(test["x"][5:10]), you can call the plot method of Series object:

plot(test["x"][5:10])您可以调用 Series 对象的 plot 方法,而不是调用:

test["x"][5:10].plot()

The reason: test["x"][5:10]is a Series object with integer index from 5 to 10. plot()try to get index 0 of it, that will cause error.

原因:test["x"][5:10]是一个整数索引从 5 到 10 的 Series 对象。plot()尝试获取它的索引 0,这将导致错误。

回答by citynorman

I encountered this error with pd.groupbyin Pandas 0.14.0 and solved it with df = df[df['col']!= 0].reset_index()

pd.groupby在 Pandas 0.14.0 中遇到了这个错误并用df = df[df['col']!= 0].reset_index()