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
>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