这是我的功能:
def get_month(date_string, kind = 'month'):
if kind == 'month':
date = datetime.datetime.strptime(date_string, '%Y-%m')
elif kind == 'day':
date = datetime.datetime.strptime(date_string, '%Y-%m-%d')
return date.strftime("%B")
我在这里调用了函数:
data['purchase_month'] = data['purchase_date'].apply(lambda x: get_month(x, kind = 'day'))
data['first_active_month2'] = data['first_active_month'].apply(lambda x:get_month(x))
data['first_active_year'] = data['first_active_month'].str[:4]
我调用函数以获得一个月的第二行给我这个错误:已编辑
Traceback (most recent call last)
<ipython-input-79-bb17fedd582e> in <module>()
20
21 data['purchase_month'] = data['purchase_date'].apply(lambda x:get_month(x, kind = 'day'))
---> 22 data['first_active_month2'] =data['first_active_month'].apply(lambda x: get_month(x))
23 data['first_active_year'] = data['first_active_month'].str[:4]
24
/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
3192 else:
3193 values = self.astype(object).values
-> 3194 mapped = lib.map_infer(values, f,convert=convert_dtype)
3195
3196 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-79-bb17fedd582e> in <lambda>(x)
20
21 data['purchase_month'] = data['purchase_date'].apply(lambda x:get_month(x, kind = 'day'))
---> 22 data['first_active_month2'] =data['first_active_month'].apply(lambda x: get_month(x))
23 data['first_active_year'] = data['first_active_month'].str[:4]
24
<ipython-input-79-bb17fedd582e> in get_month(date_string, kind)
14 def get_month(date_string, kind = 'month'):
15 if kind == 'month':
---> 16 date = datetime.datetime.strptime(date_string, '%Y-%m')
17 elif kind == 'day':
18 date = datetime.datetime.strptime(date_string, '%Y-%m-%d')
/opt/conda/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format)
563 """Return a class cls instance based on the input string and the
564 format string."""
--> 565 tt, fraction = _strptime(data_string, format)
566 tzname, gmtoff = tt[-2:]
567 args = tt[:6] + (fraction,)
/opt/conda/lib/python3.6/_strptime.py in _strptime(data_string, format)
363 if len(data_string) != found.end():
364 raise ValueError("unconverted data remains: %s" %
--> 365 data_string[found.end():])
366
367 iso_year = year = None
ValueError: unconverted data remains: -01
我不知道我在这方面做错了什么。我已经尝试过在Stackoverflow上找到的其他解决方案,但是似乎都没有用。