Pd.to_datetime 返回一个对象,而不是时间序列 [英] Pd.to_datetime returns an object, not a time series
问题描述
我正在尝试将 df 中的列转换为时间序列.数据集从 2015 年 3 月 23 日到 2019 年 8 月 17 日,数据集如下所示:
I am trying to convert my column in a df into a time series. The dataset goes from March 23rd 2015-August 17th 2019 and the dataset looks like this:
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
我试图将时间列转换为日期时间系列,但它将该列作为对象返回.代码如下:
I am trying to convert the time column into a datetime series but it returns the column as an object. Here is the code:
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.index.dtype returns dtype('O'). I assume this is why when I try to index an element in time, it returns an error. For example, when I run this:
data.loc['2015']
它给了我这个错误
KeyError: '2015'
任何帮助或反馈将不胜感激.谢谢.
Any help or feedback would be appreciated. Thank you.
推荐答案
正如所评论的,问题可能是由于时区不同造成的.尝试将 utc=True
传递给 pd.to_datetime
:
As commented, the problem might be due to the different timezones. Try passing utc=True
to 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
这篇关于Pd.to_datetime 返回一个对象,而不是时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!