【问题标题】:pandas key error when manipulating columns with time series column name使用时间序列列名操作列时出现熊猫键错误
【发布时间】:2020-02-18 11:28:30
【问题描述】:

我在检索具有日期时间列名称的 pandas 列时遇到了关键错误。 谁能给我一些解决这个问题的建议? 详情如下:

1.我有一个这样的数据框: (样本数据)

        store    2019-11 00:00:00  2019-12 00:00:00  2020-01 00:00:00
    0   a          500                 10000                20000
    1   b          500                 20000                25000
    2   c          600                 30000                30000
  1. 我的目的是进行以下计算:
    • 总结过去24个月的数据
    • 汇总年末数据(如果是2020年2月,只检索2020年1月和2月)

3.为了使操作更容易,我将子集列转换为日期

df.columns = GC_df.columns[:5].tolist() + pd.to_datetime(df.columns[5:]).to_period('M').tolist()

4.当我尝试检索特定月份的数据时,发生了一个关键错误: 打印(GC_df.loc[:,"2016-03"])

错误信息:

    `KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '2016-03'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-62-dd7e58799d99> in <module>
      1 #print(GC_df.head())
----> 2 print(GC_df.loc[:,"2016-03"])

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1492             except (KeyError, IndexError, AttributeError):
   1493                 pass
-> 1494             return self._getitem_tuple(key)
   1495         else:
   1496             # we by definition only have the 0th axis

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
    866     def _getitem_tuple(self, tup):
    867         try:
--> 868             return self._getitem_lowerdim(tup)
    869         except IndexingError:
    870             pass

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
    986         for i, key in enumerate(tup):
    987             if is_label_like(key) or isinstance(key, tuple):
--> 988                 section = self._getitem_axis(key, axis=i)
    989 
    990                 # we have yielded a scalar ?

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1911         # fall thru to straight lookup
   1912         self._validate_key(key, axis)
-> 1913         return self._get_label(key, axis=axis)
   1914 
   1915 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
    139             raise IndexingError('no slices here, handle elsewhere')
    140 
--> 141         return self.obj._xs(label, axis=axis)
    142 
    143     def _get_loc(self, key, axis=None):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3574 
   3575         if axis == 1:
-> 3576             return self[key]
   3577 
   3578         self._consolidate_inplace()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '2016-03'`

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    .to_period返回Period index不是string

    用途:

    pd.to_datetime(df.columns[5:], format = '%Y-%m %H:%M:%S').strftime('%Y-%m').tolist()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-07
      • 2019-03-06
      • 2014-10-08
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多