I am try to use apply function on pandas series which works fine when the function is not nested.
def valid_date(datestring):
try: return datetime.datetime.strptime(datestring, '%m-%d-%y').date() # 02-22-99
except ValueError:
try: return datetime.datetime.strptime(datestring, '%m/%d/%Y').date() #02/22/1999
except ValueError:
pass
return False
bs.apply(valid_date)
The output of the above gives what I want
0 1993-03-25
1 1985-06-18
2 1971-07-08
3 1975-09-27
4 1996-02-06
5 1979-07-06
6 1978-05-18
7 1989-10-24
Length: 8, dtype: object
bs is series
0 03/25/93
1 6/18/85
2 7/8/71
3 9/27/75
4 2-6-96
5 7-06-79
6 5/18/78
7 10/24/89
Length: 8, dtype: object
But when nested in a function it returns
TypeError: strptime() argument 1 must be str, not float
Nested function is
def dateApply():
def valid_date(datestring):
try: return datetime.datetime.strptime(datestring, '%m-%d-%y').date() # 02-22-99
except ValueError:
try: return datetime.datetime.strptime(datestring, '%m/%d/%Y').date() #02/22/1999
except ValueError:
pass
return False
bd=bs.apply(valid_date)
return bd.sort_values()
Note: It is necessary for me to nest the function. Also, since I have variety of date formats I cannot use pd.to_datetime() and have to revert to nested try-except block