【问题标题】:apply lambda function error for date issue对日期问题应用 lambda 函数错误
【发布时间】: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


【解决方案1】:

仔细阅读你的错误它说:“'datetime.date'对象不可下标”所以你的'join_date'是dtypedatetime.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)

【讨论】:

    【解决方案2】:

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

    emp['join_date'].dt.month
    

    利用这种方法,您无需处理两位数月份。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2021-11-20
      • 2022-01-01
      • 1970-01-01
      • 2020-02-15
      • 1970-01-01
      • 2013-01-23
      相关资源
      最近更新 更多