我正在尝试将 df 中的列转换为时间序列。数据集从 2015 年 3 月 23 日到 2019 年 8 月 17 日,数据集如下所示:
time 1day_active_users
0 2015-03-23 00:00:00-04:00 19687.0
1 2015-03-24 00:00:00-04:00 19437.0
我正在尝试将时间列转换为日期时间系列,但它会将列作为对象返回。这是代码:
data = pd.read_csv(data_path)
data.set_index('time', inplace=True)
data.index= pd.to_datetime(data.index)
data.index.dtype
data.index.dtype 返回 dtype('O')。我想这就是为什么当我尝试及时索引一个元素时,它会返回一个错误。例如,当我运行这个时:
data.loc['2015']
它给我这个错误
KeyError: '2015'
如有任何帮助或反馈,我们将不胜感激。谢谢。
最佳答案
如评论所述,问题可能是由于时区不同造成的。尝试将 utc=True
传递给 pd.to_datetime
:
df['time'] = pd.to_datetime(df['time'],utc=True)
df['time']
测试数据
time 1day_active_users
0 2015-03-23 00:00:00-04:00 19687.0
1 2015-03-24 00:00:00-05:00 19437.0
输出:
0 2015-03-23 04:00:00+00:00
1 2015-03-24 05:00:00+00:00
Name: time, dtype: datetime64[ns, UTC]
然后:
df.set_index('time', inplace=True)
df.loc['2015']
给予
1day_active_users
time
2015-03-23 04:00:00+00:00 19687.0
2015-03-24 05:00:00+00:00 19437.0
关于python - pd.to_datetime 返回一个对象,而不是时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326801/