【发布时间】:2021-08-22 16:05:50
【问题描述】:
我正在尝试从下面的 join_date 中提取月份。下面是emp表的结构。我在执行以下代码时遇到错误:
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'
【问题讨论】:
-
仔细阅读你的错误,上面写着
'datetime.date' object is not subscriptable所以你的'join_date'是dtype datetime.date所以使用emp['join_date'].astype(str).str[:7]
标签: pandas dataframe lambda apply series