首页 > 解决方案 > 应用函数在嵌套函数中不起作用

问题描述

我尝试在 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 块

标签: pandasdatetimeapplydatetime-format

解决方案


推荐阅读