Home > Software design >  KeyError in pandas to_datetime
KeyError in pandas to_datetime

Time:09-21

I am loading a csv file which have datetime, when trying to convert using df['times'] = pd.to_datetime(df['times'], format='%Y-%m-%d %H:%M:%S') its giving keyerror. Also please find the of Jupyter notebook Jupyter notebook

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/Software/Anytrader/venv/lib/python3.6/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: 'times'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-6-4f05a9476911> in <module>
----> 1 df['times'] = pd.to_datetime(df['times'], format='%Y-%m-%d %H:%M:%S')
      2 df.dtypes

~/Software/Anytrader/venv/lib/python3.6/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]

~/Software/Anytrader/venv/lib/python3.6/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: 'times'

CodePudding user response:

From your screenshot, it looks like your column names include quotes. Try this:

df["'times'"] = pd.to_datetime(df["'times'"], format='%Y-%m-%d %H:%M:%S')

Alternatively (and probably better), you could strip the quotes from your column names right after loading the data from the file.

df.columns = df.columns.str.strip("'")
  • Related