我有一个数据集,我想更改名为“Last Updated”的列的格式。
DB['Last Updated'].head()
0 January 7, 2018
1 January 15, 2018
2 August 1, 2018
3 June 8, 2018
4 June 20, 2018
Name: Last Updated, dtype: object
我想制作像7/1/2018这样的格式,所以我在python中编写了以下内容。
DB['Last Updated'] = pd.to_datetime(DB['Last Updated'],format= '%d/%m/%Y')
但是出现此错误:
TypeError Traceback (most recent call last) ~/anaconda3/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in _convert_listlike(arg, box, format, name, tz)
302 try:
--> 303 values, tz = tslib.datetime_to_datetime64(arg)
304 return DatetimeIndex._simple_new(values, name=name, tz=tz)
pandas/_libs/tslib.pyx in pandas._libs.tslib.datetime_to_datetime64()
TypeError: Unrecognized value type:
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
in ()
----> 1 DB['Last Updated'] = pd.to_datetime(DB['Last Updated'],format= '%d/%m/%Y')
~/anaconda3/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin)
371 elif isinstance(arg, ABCSeries):
372 from pandas import Series
--> 373 values = _convert_listlike(arg._values, True, format)
374 result = Series(values, index=arg.index, name=arg.name)
375 elif isinstance(arg, (ABCDataFrame, MutableMapping)):
~/anaconda3/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in _convert_listlike(arg, box, format, name, tz)
304 return DatetimeIndex._simple_new(values, name=name, tz=tz)
305 except (ValueError, TypeError):
--> 306 raise e
307
308 if arg is None:
~/anaconda3/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in _convert_listlike(arg, box, format, name, tz)
271 try:
272 result = array_strptime(arg, format, exact=exact,
--> 273 errors=errors)
274 except tslib.OutOfBoundsDatetime:
275 if errors == 'raise':
pandas/_libs/tslibs/strptime.pyx in pandas._libs.tslibs.strptime.array_strptime()
ValueError: time data 'January 7, 2018' does not match format '%d/%m/%Y' (match)
我该如何处理这个错误?
该format参数在pd.to_datetime(...)用于指定要从转换字符串的格式(未指定输出格式)。为了将日期字符串转换为datetime对象,然后转换为特定的输出格式,您可以执行以下操作:
import pandas as pd
data = [{'Last Updated': 'January 7, 2018'}, {'Last Updated': 'January 15, 2018'}]
df = pd.DataFrame(data)
df['Last Updated'] = pd.to_datetime(df['Last Updated'])
df['Last Updated'] = df['Last Updated'].dt.strftime('%d/%m/%Y')
print(df)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。