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

verify which part of dataframe string cannot convert to string

I have a dataframe like this

from datetime import datetime

df1=pd.DataFrame({'date':['2016-02-02','2013','2015-02-03','2014-03-02']})
try:
    pd.to_datetime(df1)
except ValueError:
  print("second is wrong")

we see that second value is not valid data format for datetime %Y-%m-%d
so what should I wrote to create desired output like this with pandas method

true
false 
true 
true

rather than using

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

try:
    res = bool(datetime.strptime(test_str, format))
except ValueError:
    res = False

to testing the whole dataframe with a for loop?

>Solution :

try and except is actually good practice. You can wrap it into a function which you can apply:

import pandas as pd
from datetime import datetime


def datetime_if_possible(dt):
    try:
        return datetime.fromisoformat(dt)
    except ValueError:
        return None  # or any other default value


df1 = pd.DataFrame({'date':['2016-02-02','2013','2015-02-03','2014-03-02']})

df1['parsed'] = df1['date'].apply(datetime_if_possible)

         date     parsed
0  2016-02-02 2016-02-02
1        2013        NaT
2  2015-02-03 2015-02-03
3  2014-03-02 2014-03-02
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