当前位置: 首页 > 面试题库 >

使用日期时间绘制切片的pandas数据框时发生KeyError

方夜洛
2023-03-14
问题内容

当我尝试绘制其中包含日期时间的pandas DataFrame列的切片时出现KeyError。有人知道是什么原因造成的吗?

我设法在一个独立的示例中重现了该错误(您也可以在这里查看: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)})

现在,如果我绘图:

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

没问题,但是当我绘图时:

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

我在下面看到KeyError(错误消息对我不是很有帮助)。这 仅在datetime 列中 发生 ,而在其他列中则不 发生
(据我所知)。例如,plot(test['y'][5:10])这不是问题。

错误消息:

---------------------------------------------------------------------------
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

问题答案:

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>]

用0.7.3一口气绘制x,y

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


 类似资料:
  • 问题内容: 场景: 我有一个从Excel工作表中检索到具有多个列的数据框。其中一些列是日期:一些仅包含日期(yyyy:mm:dd),一些具有日期和时间戳(yyyy:mm:dd 00.00.000000)。 问题: 当日期不是数据框的索引时,如何从日期中删除时间戳? 我已经尝试了什么: 在SO的其他文章中使用pandas中的日期- 在datetime中删除看不见的字符并转换为字符串以及如何剥离pan

  • 问题内容: 我有一列希望按日期时间分组而不创建新列。这可能是我当前的代码不起作用吗? 问题答案: 正如@JosephCottam所建议的 过时的用途 您可以将索引设置为并使用

  • 本文向大家介绍pandas 日期时间系列,包括了pandas 日期时间系列的使用技巧和注意事项,需要的朋友参考一下 示例            

  • 问题内容: 我有一个数据框,其中一列用于时区,一列用于日期时间。我想先将它们转换为UTC并与其他数据合并,然后我将进行一些计算以最终从UTC转换为观看者的本地时区。 那是我的错误尝试。错误是事实不明确,这是有道理的,因为“时区”变量引用的是列。如何引用同一行中的值? 编辑:这是一天数据的下面答案的一些结果(394,000行和22个唯一时区)。Edit2:我添加了一个groupby示例,以防有人想要

  • 问题内容: 假设我使用以下方法创建一个完全随机的“Dataframe”: 这将导致数据帧显示在这篇文章的底部。我想 使用 时间序列 “seaborn”中的可视化功能使我得到了以下线索 我如何解决这个问题?从我读到的 笔记本](http://www.stanford.edu/~mwaskom/software/seaborn/timeseries_plots.html), 电话应该是: 但这似乎需要

  • 主要内容:日期格式化符号,Python处理,Pandas处理当进行数据分析时,我们会遇到很多带有日期、时间格式的数据集,在处理这些数据集时,可能会遇到日期格式不统一的问题,此时就需要对日期时间做统一的格式化处理。比如“Wednesday, June 6, 2020”可以写成“6/6/20”,或者写成“06-06-2020。 日期格式化符号 在对时间进行格式化处理时,它们都有固定的表示格式,比如小时的格式化符号为 ,分钟简写为 ,秒简写为 。下表对常用的日期