问题描述
我尝试在pandas系列上使用apply函数,当该函数未嵌套时,效果很好。
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)
上面的输出给出了我想要的
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 是系列
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
但是当嵌套在函数中时,它会返回
TypeError: strptime() argument 1 must be str,not float
嵌套功能是
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()
注意:我有必要嵌套该函数。另外,由于我使用多种日期格式,因此无法使用pd.to_datetime(),而必须还原为嵌套的try-except块
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)