LoginSignup
1
0

【Python】to_datetimeでValueErrorエラーが出た時の解決方法

Last updated at Posted at 2023-04-14

データフレームの日付列を文字型から日付型へ変更するところで躓いたため、対策を書きました!

変更したいデータ

下の表のように存在しない日付や年度のみが混ざっている列をYYYY-MM-DDの形に変更していきます。

id 日付
0 2022/2/20
1 2022/*
2 2022/15/6
3 2022/5/6
4 2022/16/10
5 2022/22/25
6 2022/15/6

このままto_datetimeをやってみる

なにも加工していないデータを型変更するとValueエラーが発生します。

 import pandas as pd

# test用のデータフレーム
df= pd.DataFrame(data={
    'id': [0,1,2,3,4,5,6],
    '日付':["2022/2/20","2022/*","2022/15/6","2022/5/6", "2022/16/10", "2022/22/25", "2022/15/6"]
})

# 変換
df['日付'] = pd.to_datetime(df['日付'], format='%Y-%m-%d')

ValueError: time data "2022/15/6" at position 1 doesn't match format specified

存在しない日付があるとエラーが出てしまいす。
下の表の日付達が犯人!

id 日付
1 2022/*
2 2022/15/6
4 2022/16/10
5 2022/22/25
6 2022/15/6

errorsを設定して解決

to_datetimeにerrors='coerce'を追加してあげるだけ!
これで存在しない日付はNaTに変換してくれます。

df['日付'] = pd.to_datetime(df['日付'], format='%Y-%m-%d',errors='coerce')

おまけ

NaTは直前の値を入れることで埋めました!

df['日付'] = pd.to_datetime(df['日付'], format='%Y-%m-%d',errors='coerce')
id 日付
0 2022-02-20
1 2022-02-20
2 2022-02-20
3 2022/05/06
4 2022/05/06
5 2022/05/06
6 2022/05/06

終わりに

簡単にValueErrorを解決する方法を書きました。

初学者なので情報に誤りがあるかもしれません。
ご容赦ください🙇

最後まで読んでいただきありがとうございます!

参考ページ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0