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

Can't apply a function because I have NaN

I’m trying to change the date format to a column but I cant apply my function because I have NaN cells.

# change date format
def dmy_to_dmy(d):
    return datetime.strptime(d, '%d %B %Y').strftime('%d/%m/%Y')

dates2['Dates_Reins'] = dates2['Dates_Reins'].apply(dmy_to_dmy)

My data looks like this:

46  9 September 2021
47  NaN
48  24 July 2021
49  28 September 2021
50  18 October 2021
51  8 January 2021
52  NaN

Thanks

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

>Solution :

There are two options, ingoring the problem or detecting the problem. The first one is the easy one since you try and pass if it doesn’t happen. The second one will detect the NaN

First solution

# change date format
def dmy_to_dmy(d):
    try:
        return datetime.strptime(d, '%d %B %Y').strftime('%d/%m/%Y')
    except TypeError:
        return d
    
dates2['Dates_Reins'] = dates2['Dates_Reins'].apply(dmy_to_dmy)

Second solution

# change date format
def dmy_to_dmy(d):
    if d == np.nan:
        return d
    else:
        return datetime.strptime(d, '%d %B %Y').strftime('%d/%m/%Y')
    
dates2['Dates_Reins'] = dates2['Dates_Reins'].apply(dmy_to_dmy)

Since you haven’t provided the data d==np.nan you have to find for yourself

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