pandas - 应用函数在嵌套函数中不起作用
问题描述
我尝试在 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 块
解决方案
推荐阅读
- c - 在 C 中,为什么尽管在代码中提到了我在链表节点内的 scanf 输入却没有被采用?
- php - Laravel 多个命名的可选参数,其中顺序无关紧要
- java - 将 Spring boot JPA(MySQL) 迁移到 JPA(PostgreSQL) 会引发错误
- c# - .net core API 发送数组对象
- java - 在运行时检测 Android 手机上的 java 版本
- ios - 使用带有 UIActivityViewController 的 PHLivePhoto
- sql-server - Delphi DBExpress 与 Devart SQL Server 驱动程序如何连接到数据库
- node.js - 如何将 Express Web 项目转换为窗口独立应用程序
- laravel - 如何将带 id 的 href 传递给控制器方法 Laravel
- java - Nexus 6P 上硬件传感器的 Android 采样率变化