我正在导入Excel文件,其中“日期”列有不同的书写方式:
Date
13/03/2017
13/03/2017
13/03/2017
13/03/2017
10/3/17
10/3/17
9/3/17
9/3/17
9/3/17
9/3/17
导入到熊猫:
df = pd.read_excel('data_excel.xls')
df.Date = pd.to_datetime(df.Date)
结果是:
Date
13/03/2017
64 13/03/2017
65 13/03/2017
66 13/03/2017
67 2017-10-03 00:00:00
68 2017-10-03 00:00:00
69 2017-09-03 00:00:00
70 2017-09-03 00:00:00
71 2017-09-03 00:00:00
72 2017-09-03 00:00:00
这意味着,pandas 没有正确解析日期和时间:
10/3/17 -> 2017-10-03
当我尝试指定格式时:
df.Date = pd.to_datetime(df.Date, format='%d%m%Y')
收到错误:
ValueError: time data u'13/03/2017' does not match format '%d%m%Y' (match)
问题:
如何将Excel文件中的日期和时间正确导入到pandas中?
新答案:
实际上pd.to_datetime
has a dayfirst
此处有用的关键字参数:
df.Date = pd.to_datetime(df.Date,dayfirst=True)
Result:
>>> df.Date
0 2017-03-13
1 2017-03-13
2 2017-03-13
3 2017-03-13
4 2017-03-10
5 2017-03-10
6 2017-03-09
7 2017-03-09
8 2017-03-09
9 2017-03-09
Name: Date, dtype: datetime64[ns]
旧答案:
使用第三方模块dateutil http://dateutil.readthedocs.io/en/stable/index.html它可以处理这些类型的变化。它有一个dayfirst
此处有用的关键字参数:
import dateutil
df = pd.read_excel('data_excel.xls')
df.Date = df.Date.apply(lambda x: dateutil.parser.parse(x,dayfirst=True))
Result:
>>> df.Date
0 2017-03-13
1 2017-03-13
2 2017-03-13
3 2017-03-13
4 2017-03-10
5 2017-03-10
6 2017-03-09
7 2017-03-09
8 2017-03-09
9 2017-03-09
Name: Date, dtype: datetime64[ns]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)