I am trying to change the data type of a column from object to date in pandas dataframe. I cannot control the data type with dtypes because both the string(text) and date data are of object type. (I shouldn't use Try Except). Can I find out if the selected column contains string values without using Try Except?
2 Answers
Pandas's to_datetime() has an errors argument. You can set it to 'coerce', for instance, to turn bad dates into NaT.
df = pd.DataFrame({'t': ['20200101', '2020-01-01', 'foobar', '2020-01-01T12:17:00.333']})
pd.to_datetime(df['t'], errors='coerce')
# out:
0 2020-01-01 00:00:00.000
1 2020-01-01 00:00:00.000
2 NaT
3 2020-01-01 12:17:00.333
Name: t, dtype: datetime64[ns]
1 Comment
uckocaman
I knew this parameter. I wanted no convert in that column if there is a string value, so I wanted to check it. Thank you for the answer I can use that too.
Try this to convert object to datetime
df[col] = pd.to_datetime(df[col], errors='coerce')
1 Comment
uckocaman
I knew this parameter. I wanted no convert in that column if there is a string value, so I wanted to check it. Thank you for the answer I can use that too.