Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting string to date format 0000-00-00 before extracting year and month information

I have a string column (object type):

Date
2020-06-15
2019-07-23
Data non available

How can I convert the string Data non available and/or any missing values to the format 0000-00-00, before extracting the month and the year?

I can convert the Date column to datetime, and extract information on year and month from the other rows, but then I get this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ParserError: Unknown string format: Data not available

My code:

df['Date'] = pd.to_datetime(df['Date'])
df['Date_Year'], df['Date_month'] = df['Date'].dt.year, df['Date'].dt.month

Expected output:

Date             Date_Year        Date_month
2020-06-15          2020              06
2019-07-23          2019              07
Data non available  0000              00

>Solution :

I’d replace Data not available with NaT (Not A Time – NaN equivalent for dates/times) before you call to_datetime:

df['Date'] = df['Date'].replace({'Data non available': pd.NaT})

Then

df['Date'] = pd.to_datetime(df['Date'])
df['Date_Year'], df['Date_month'] = df['Date'].dt.year, df['Date'].dt.month

Output:

>>> df
        Date  Date_Year  Date_month
0 2020-06-15     2020.0         6.0
1 2019-07-23     2019.0         7.0
2        NaT        NaN         NaN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading