为日期问题应用 lambda 函数错误

apply lambda function error for date issue

我正在尝试从下面的 join_date 中提取月份。下面是 emp table 的结构。我在执行以下代码时遇到错误:

emp['join_mth']=emp['join_date'].apply(lambda x:x[:7])

emp_id emp_name account_id join_date
1       rob     121         2019-01-01
2       sam     122         2019-02-02
3       mike    123         2019-03-03
4       tom     124         2019-04-04 

type(emp['join_date'])
<class 'pandas.core.series.Series'>

emp.dtypes
emp_id          object
emp_name        object  
account_id      object
join_date       object
dtype:object

fail to excute line - 10: emp['join_mth']=emp['join_date'].apply(lambda x:x[:7])

下面是准确的错误:

Traceback (most recent call last):
  File "<stdin>", line 39, in <module>
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/_libs/lib.pyx", line 2467, in pandas._libs.lib.map_infer
  File "<stdin>", line 39, in <lambda>
TypeError: 'datetime.date' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 70, in <module>
AttributeError: module 'sys' has no attribute 'last_value'

你的column不是字符串而是datetime对象,使用相关方法pandas.Series.dt.month,可以直接获取月份数:

emp['join_date'].dt.month

利用此方法,因为您不需要处理两位数的月份。

仔细阅读你的错误,它说:“'datetime.date' 对象不可订阅”所以你的 'join_date' 是 dtype datetime.date 所以首先使用类型转换为字符串:

emp['join_mth']=emp['join_date'].astype(str).str[:7]
#OR
emp['join_mth']=emp['join_date'].astype(str).apply(lambda x:x[:7])

因为它是 datetime.date 类型所以你也可以使用:

emp['join_date']=[x.strftime("%Y-%m") for x in emp['join_date']]
#OR
emp['join_mth']=emp['join_date'].map(lambda x:x.strftime("%Y-%m"))

如果你只想提取然后使用:

emp['join_date']=[x.strftime("%m") for x in emp['join_date']]
#emp['join_date'].apply(lambda x:x.strftime("%m"))
#OR(use above code for string format and below for int format)
emp['join_date']=[x.month for x in emp['join_date']]
#emp['join_date'].map(lambda x:x.month)