Search code examples
pythonpandasdataframedatetimekeyerror

loc() funktion wont read Datetime date.today to split panda DataFrame. (Keyerror)


I have a panda dataframe and want to extract data by date. If i use the loc() funktion with the date like

data_today = data.loc["2020-07-20"]

it will work and show the right data. But if I use a datetime it wont work.

import datetime as dt
from datetime import datetime , timedelta

date_today = dt.date.today() - dt.timedelta(days=5)
print(date_today)

data_today = data.loc["date_today"]
data_today

If I print date_today the format is the format of the DataFrame "2020-07-20" for example.

Thanks for the Help

Here the full code and errormessage

import datetime as dt
from datetime import datetime , timedelta

data = pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv" , index_col = "date")
data.head()


date_today = dt.date.today() - dt.timedelta(days=5)
print(date_today)

data_today = data.loc["date_today"]
data_today

and the error

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             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\index.pyx in pandas._libs.index.IndexEngine._get_loc_duplicates()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine._maybe_get_bool_indexer()

KeyError: 'date_today'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-179-6abf305e8190> in <module>
      5 print(date_today)
      6 
----> 7 data_today = data.loc["date_today"]
      8 data_today

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1765 
   1766             maybe_callable = com.apply_if_callable(key, self.obj)
-> 1767             return self._getitem_axis(maybe_callable, axis=axis)
   1768 
   1769     def _is_scalar_access(self, key: Tuple):

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1962         # fall thru to straight lookup
   1963         self._validate_key(key, axis)
-> 1964         return self._get_label(key, axis=axis)
   1965 
   1966 

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
    622             raise IndexingError("no slices here, handle elsewhere")
    623 
--> 624         return self.obj._xs(label, axis=axis)
    625 
    626     def _get_loc(self, key: int, axis: int):

~\anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3535             loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
   3536         else:
-> 3537             loc = self.index.get_loc(key)
   3538 
   3539             if isinstance(loc, np.ndarray):

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         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\index.pyx in pandas._libs.index.IndexEngine._get_loc_duplicates()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine._maybe_get_bool_indexer()

KeyError: 'date_today'

Solution

  • Your code should work fine, you just need to format date_today properly.

    data.loc[date_today.strftime("%Y-%m-%d")]