pandas 将熊猫日期时间索引向前一天设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27524169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:46:10  来源:igfitidea点击:

Set pandas datetime index one day forward

pythondatetimepandas

提问by Uninvited

Is it possible to set one day forward a datetime index in pandas?

是否可以在 Pandas 中设置一个日期时间索引?

I've got this index

我有这个索引

mydata.data.index
Out[7]: <class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-27 22:00:00, ..., 2014-12-16 22:00:00]
Length: 500, Freq: None, Timezone: None

and its wrong. The correct date that the data begin is the day after. That is 2014-12-17 and they end at 2013-01-28

它是错误的。数据开始的正确日期是后一天。那是 2014-12-17,它们在 2013-01-28 结束

Is there a way to fix this?

有没有办法来解决这个问题?

回答by joris

Some different options:

一些不同的选择:

Use the shiftmethod:

使用shift方法:

In [10]: dti = pd.date_range('2012-01-01', periods=2)

In [11]: dti
Out[11]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-01, 2012-01-02]
Length: 2, Freq: D, Timezone: None

In [13]: dti.shift(1, freq='D')
Out[13]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-02, 2012-01-03]
Length: 2, Freq: D, Timezone: None

But maybe more easy (as @Evert notices), you can simply add a timedelta of one day:

但也许更容易(正如@Evert 所通知的那样),您可以简单地添加一天的时间增量:

In [14]: dti + pd.Timedelta('1 day')
Out[14]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-02, 2012-01-03]
Length: 2, Freq: None, Timezone: None

For older pandas versions, you can also just use datetime.timedelta(days=1)(pd.Timedeltais only avaible starting from 0.15).

对于较旧的 Pandas 版本,您也可以使用datetime.timedelta(days=1)(pd.Timedelta仅从 0.15 开始可用)。