zhiyuan6600 2024-03-05 11:33 采纳率: 100%
浏览 3
已结题

pandas时间序列索引报错的问题

    #执行以下代码没有问题    
    ts_data_load= pd.read_csv(os.path.join(data_dir, "energy.csv"), parse_dates=["timestamp"] )

    # Reindex the dataframe such that the dataframe has a record for every time point
    # between the minimum and maximum timestamp in the time series. This helps to
    # identify missing time periods in the data (there are none in this dataset).
    ts_data_load.index = ts_data_load["timestamp"]
    ts_data_load = ts_data_load .reindex( pd.date_range(min(energy["timestamp"]), max(energy["timestamp"]), freq="H")  )
    ts_data_load= ts_data_load .drop("timestamp", axis=1)
    ts_data_load = load_data(data_dir)[["load"]]
    ts_data_load.head()
    #输出结果

load
2012-01-01 00:00:00 2,698.00
2012-01-01 01:00:00 2,558.00
2012-01-01 02:00:00 2,444.00
2012-01-01 03:00:00 2,402.00
2012-01-01 04:00:00 2,403.00

#执行下面这句代码,输出正常  
ts_data_load.index
#输出结果
DatetimeIndex(['2012-01-01 00:00:00', '2012-01-01 01:00:00',
               '2012-01-01 02:00:00', '2012-01-01 03:00:00',
               '2012-01-01 04:00:00', '2012-01-01 05:00:00',
               '2012-01-01 06:00:00', '2012-01-01 07:00:00',
               '2012-01-01 08:00:00', '2012-01-01 09:00:00',
               ...
               '2014-12-31 14:00:00', '2014-12-31 15:00:00',
               '2014-12-31 16:00:00', '2014-12-31 17:00:00',
               '2014-12-31 18:00:00', '2014-12-31 19:00:00',
               '2014-12-31 20:00:00', '2014-12-31 21:00:00',
               '2014-12-31 22:00:00', '2014-12-31 23:00:00'],
              dtype='datetime64[ns]', length=26304, freq='H')
    #如果执行下面这句代码,就报错
    ts_data_load['2012-06-01']
    #报错,请问这是什么原因??谢谢

KeyError Traceback (most recent call last)
File d:\ProgramData\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3653, in Index.get_loc(self, key)
3652 try:
-> 3653 return self._engine.get_loc(casted_key)
3654 except KeyError as err:

File d:\ProgramData\anaconda3\Lib\site-packages\pandas_libs\index.pyx:147, in pandas._libs.index.IndexEngine.get_loc()

File d:\ProgramData\anaconda3\Lib\site-packages\pandas_libs\index.pyx:176, in pandas._libs.index.IndexEngine.get_loc()

File pandas_libs\hashtable_class_helper.pxi:7080, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas_libs\hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '20120601'

The above exception was the direct cause of the following exception:

KeyError Traceback (most recent call last)
Cell In[33], line 1
----> 1 ts_data_load['20120601']

File d:\ProgramData\anaconda3\Lib\site-packages\pandas\core\frame.py:3761, in DataFrame.getitem(self, key)
3759 if self.columns.nlevels > 1:
3760 return self._getitem_multilevel(key)
-> 3761 indexer = self.columns.get_loc(key)
3762 if is_integer(indexer):
3763 indexer = [indexer]

File d:\ProgramData\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3655, in Index.get_loc(self, key)
3653 return self._engine.get_loc(casted_key)
3654 except KeyError as err:
-> 3655 raise KeyError(key) from err
3656 except TypeError:
3657 # If we have a listlike key, _check_indexing_error will raise
3658 # InvalidIndexError. Otherwise we fall through and re-raise
3659 # the TypeError.
3660 self._check_indexing_error(key)

KeyError: '20120601'

  • 写回答

3条回答 默认 最新

  • GISer Liu 2024-03-05 11:34
    关注

    该回答引用自GPT-3.5,由博主GISer Liu编写:

    根据问题描述,报错信息显示KeyError: '20120601',这意味着在尝试使用ts_data_load['20120601']这样的语法时发生了错误,因为该索引值无法在DataFrame中找到。问题的根本原因是尝试使用字符串``` '20120601'

    解决方案如下:
    1.  **索引时使用时间戳对象而不是字符串** :确保使用正确的时间戳对象进行索引,而不是字符串。在pandas中,使用``` pd.Timestamp('2012-06-01') ```来表示时间戳对象。
    2.  **转换索引为时间戳对象** :在读取CSV文件后,将DataFrame的索引转换为时间戳对象,以便正确地使用时间戳进行索引。
    下面是解决问题的具体代码:
    pythonCopy code
    

    确保正确导入所需的库

    import pandas as pd
    import os

    读取CSV文件,确保parse_dates参数正确解析时间戳列

    ts_data_load = pd.read_csv(os.path.join(data_dir, "energy.csv"), parse_dates=["timestamp"])

    将索引转换为时间戳对象

    ts_data_load.index = pd.to_datetime(ts_data_load["timestamp"])

    删除'timestamp'列,因为索引已经包含了这个信息

    ts_data_load = ts_data_load.drop("timestamp", axis=1)

    现在可以使用时间戳对象进行索引

    例如,获取2012年6月1日的数据

    ts_data_load.loc['2012-06-01']

    或者使用pd.Timestamp('2012-06-01')进行索引

    ts_data_load.loc[pd.Timestamp('2012-06-01')]

    ```
    以上代码会正确地索引到2012年6月1日的数据,避免了报错。
    这样的修改可以确保代码在进行时间序列数据索引时不会出现错误,并且能够按预期工作。

    如果该回答解决了您的问题,请采纳!如果没有,请参考以下方案进行修订

    用户答题指南

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月13日
  • 已采纳回答 3月5日
  • 创建了问题 3月5日

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据