#python #pandas
Вопрос:
Я пытался преобразовать даты в datetime, поскольку они были предоставлены мне в формате ГГГГММДД на моем HW. Дата уже была проиндексирована для предыдущей проблемы, поэтому я выписал:
df.reset_index()
df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')
Это сообщение об ошибке, которое я в итоге получил:
KeyError Traceback (most recent call last)
~anaconda3libsite-packagespandascoreindexesbase.py in
get_loc(self, key, method, tolerance)
3079 try:
-> 3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libshashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas_libshashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'DATE'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-291-e5a2ae2efa46> in <module>
1 df.reset_index()
----> 2 df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')
3 #df.set_index('DATE',inplace=True)
4 #df.resample('A').apply(lambda x: x[x<0].count())
~anaconda3libsite-packagespandascoreframe.py in __getitem__(self, key)
3022 if self.columns.nlevels > 1:
3023 return self._getitem_multilevel(key)
-> 3024 indexer = self.columns.get_loc(key)
3025 if is_integer(indexer):
3026 indexer = [indexer]
~anaconda3libsite-packagespandascoreindexesbase.py in get_loc(self, key, method, tolerance)
3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
-> 3082 raise KeyError(key) from err
3083
3084 if tolerance is not None:
KeyError: 'DATE'
Very confused since I pretty much literally used this datetime line for a different problem without any issue. Is there anything I can do to fix this? thanks!
Комментарии:
1. Похоже, у вас нет
DATE
столбца. ЕслиDATE
был индекс,df.reset_index()
не получится обновить фрейм данных, чтобыDATE
он был столбцом.reset_index
по умолчанию не установлено. Возможно, вы имели в видуdf = df.reset_index()
?2. кажется, я идиот, мне просто нужно было добавить (inplace= True) после to_datetime … спасибо, что указали, что столбец ДАТЫ отсутствует! теперь, чтобы исправить другие строки, lol
3. Ты не идиот. Очень легко пропустить мелочи. Я рад, что вы немного ближе к решению.