前提
データ型(datetime)変換の練習中です
新しい列(date_time_month)の作成がうまくいなかいため、何卒ご指導ください
可能であれば、理由を教えていただけますと幸いです
実現したいこと
date_timeから年月情報を抽出し、新たに作成したdate_time_month列として格納したいです
発生している問題・エラーメッセージ
KeyError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3360 try:
-> 3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
4 frames
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: 'date_month'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
-> 3363 raise KeyError(key) from err
3364
3365 if is_scalar(key) and isna(key) and not self.hasnans:
KeyError: 'date_month'
該当のソースコード
**途中からで申し訳ございません
date_2017['date_time'] = date_2017['date'].str.cat(date_2017['time'], sep=' ')
date_2017['date_time'] = pd.to_datetime(date_2017['date_time'])
date_2018['date_time'] = date_2018['date'].str.cat(date_2018['time'], sep=' ')
date_2018['date_time'] = pd.to_datetime(date_2018['date_time'])
date = pd.concat([date_2017, date_2018], axis=0, ignore_index=True)
date = date.set_index("date_time")
##error
date['date_time'] = date['date_time_month'].dt.strftime('%Y%m')
date.groupby('date_time_month').sum()
試したこと
date_timeのdtaypeををobjectからdatetime型に変換したこと、もしくはdate_time列をindexに指定したことが原因と思い自分なりに色々調べてみましたが、自分では解決することが出来ませんでした。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

回答1件
あなたの回答
tips
プレビュー