実現したいこと
pandasでの時系列データの参照において特定の年月を指定したいのですが
書籍の記載済みのコードが正しく作動しません。
アドバイスいただけますと幸いです。
前提
ここでは、サンプルデータに含まれる2001/1/2から2016/12/30までのドル円の為替レートデータ(DEXJPUS)を使います。日ごとのレートデータで、欠損している日(休日など)もあります。
start_date = '2001/1/2'
end_date = '2016/12/30'
fx_jpusdata = pdr.DataReader('DEXJPUS', 'fred', start_date, end_date)
fx_jpusdata.head()
fx_jpusdata["2016-04"]
発生している問題・エラーメッセージ
KeyError Traceback (most recent call last)
File ~/anaconda3/lib/python3.11/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 ~/anaconda3/lib/python3.11/site-packages/pandas/_libs/index.pyx:147, in pandas._libs.index.IndexEngine.get_loc()
File ~/anaconda3/lib/python3.11/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: '2016-04'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[94], line 1
----> 1 fx_jpusdata["2016-04"]
File ~/anaconda3/lib/python3.11/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 ~/anaconda3/lib/python3.11/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: '2016-04'
該当のソースコード
fx_jpusdata["2016-04"]
補足情報(FW/ツールのバージョンなど)
