DatetimeIndex的偏移量为 [英] DatetimeIndex offset with

查看:140
本文介绍了DatetimeIndex的偏移量为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用以下代码生成的数据框:

I have a dataframe, generated with the following code:

time_index = pd.date_range(start=datetime(2013, 1, 1, 3),
                       end=datetime(2013, 1, 2, 2, 59),
                       freq='5T')
grid_columns = [u'in_brd', u'in_alt', u'out_brd', u'out_alt']  
grid_proto = pd.DataFrame(index=time_index, columns=grid_columns)

我还向该数据框添加了一些数据.

I've also added some data to this dataframe.

当我尝试在基本数据帧中使用int偏移量浏览索引时,一切都会正确:

When I'm trying to navigate through the index with int offsets in basic dataframe I get everthing correct:

In[152]: grid_proto.index[0] + 1
Out[152]: Timestamp('2013-01-01 03:05:00', tz=None)

但是,如果我尝试使用某种切片,则会收到错误消息:

But if I'm trying to work with some kind of slice, I get an error:

In[153]: z = grid_proto[pd.notnull(x.in_brd)]
In[154]: z.index[0] + 1
Traceback (most recent call last):

File "<ipython-input-151-3ce8a4e5e2d6>", line 1, in <module>
z.index[0] + 1

File "tslib.pyx", line 664, in pandas.tslib._Timestamp.__add__ (pandas\tslib.c:12372)

ValueError: Cannot add integral value to Timestamp without offset.

我知道这是因为在第一种情况下,我使用的是DatetimeIndex元素的链接,而不是标量.在第二种情况下,我得到第一个索引元素的标量Timestamp值.我说的对吗?

I understand that this is because in first case I work with a link to DatetimeIndex elements instead of scalar. And in second case I get exactly scalar Timestamp value of first index element. Am I right?

如何正确处理此偏移量? (我需要浏览这样的片段)

How to deal with this offset correctly? (I need to navigate through such slice)

推荐答案

原因是,在第一种情况下,您有一个定期的DatetimeIndex,其频率为5分钟.因此,整数1将被解释为频率的一个单位(5分钟).
在第二种情况下,由于切片的原因,您不再有常规的时间序列,并且DatetimeIndex也不再具有频率(z.index.freq将给出None,而grid_proto.index.freq将给出5分钟).

The reason is that in the first case you have a regular DatetimeIndex with a frequency of 5 minutes. So the integer 1 will be interpreted as one unit of the frequency (5 mins).
While in the second case, because of the slicing, you don't have a regular timeseries anymore, and the DatetimeIndex has no frequency anymore (z.index.freq will give None, while grid_proto.index.freq will give 5 mins).

要解决此问题,您可以明确地添加5分钟:

To solve this, you can just explicitely add 5 mins:

In [22]: import datetime as dt

In [23]: z.index[0] + dt.timedelta(minutes=5)
Out[23]: Timestamp('2013-01-01 03:05:00', tz=None)

,或者您也可以添加pd.DateOffset(minutes=5)(这将产生相同的结果).

or alternatively you can add pd.DateOffset(minutes=5) (this will give the same result).

这篇关于DatetimeIndex的偏移量为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆