Python 2.7 将datetime转换为索引
我的熊猫数据帧的结构如下:Python 2.7 将datetime转换为索引,python-2.7,pandas,Python 2.7,Pandas,我的熊猫数据帧的结构如下: date tag 0 2015-07-30 19:19:35-04:00 E7RG6 1 2016-01-27 08:20:01-05:00 ER57G 2 2015-11-15 23:32:16-05:00 EQW7G 3 2016-07-12 00:01:11-04:00 ERV7G 4 2016-02-14 00:35:21-05:00 EQW7
date tag
0 2015-07-30 19:19:35-04:00 E7RG6
1 2016-01-27 08:20:01-05:00 ER57G
2 2015-11-15 23:32:16-05:00 EQW7G
3 2016-07-12 00:01:11-04:00 ERV7G
4 2016-02-14 00:35:21-05:00 EQW7G
5 2016-03-01 00:08:59-05:00 EQW7G
6 2015-06-19 07:15:06-04:00 ER57G
7 2016-09-08 18:17:53-04:00 ER5TT
8 2016-09-03 01:53:45-04:00 EQW7G
9 2015-11-30 09:31:02-05:00 ER57G
10 2016-03-03 22:28:26-05:00 ES5TG
11 2016-02-11 10:39:24-05:00 E5P7G
12 2015-03-16 07:18:47-04:00 ER57G
...
[11015 rows x 2 columns]
date datetime64[ns, America/New_York]
tag object
dtype: object
我正在尝试将列“date”设置为索引:
df = df.set_index(pd.DatetimeIndex(df['date']))
这会产生以下错误(使用0.19)
我已经咨询过了,但我仍然无法克服这个错误。比如说,
df = df.set_index(pd.DatetimeIndex(df['date']), ambiguous='infer')
收益率:
File "pandas/tslib.pyx", line 3703, in pandas.tslib.tz_localize_to_utc (pandas/tslib.c:63553)
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from 2015-11-01 01:38:12 asthere are no repeated times
任何关于如何将datetime列转换为索引的建议都将不胜感激。如果某列的
dtype
已经是datetime
,则您可以调用set\u index
,而无需尝试从该列构造DatetimeIndex
:
df.set_index(df['date'], inplace=True)
应该可以工作,索引的数据类型被嗅出,因此不需要从这里的序列/列构造索引对象。不会
df。设置索引(df['date'],inplace=True)
可以工作吗!这非常有效。谢谢@EdChum。如果它还不是日期时间,df.set_index(pd.to_datetime(df['date']),inplace=True)
应该可以做到这一点:)
df.set_index(df['date'], inplace=True)