Python 如何正确地向pandas.tseries.index.DatetimeIndex 添加小时数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25797245/
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-08-18 23:39:57  来源:igfitidea点击:

How to properly add hours to a pandas.tseries.index.DatetimeIndex?

pythonpandasindexingtime-seriesdataframe

提问by hernanavella

I have a normal df.index that I would like to add some hours to it.

我有一个普通的 df.index,我想为其添加几个小时。

In [1]: test[1].index
Out[2]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-03-11, ..., 2014-08-14]
Length: 52, Freq: None, Timezone: None

This is how the first element looks like:

这是第一个元素的样子:

In [1]: test[1].index[0]
Out[2]: Timestamp('2010-03-11 00:00:00')

So I try this to add the hours:

所以我尝试这样添加小时数:

In [1]: test[1].index[0] + pd.tseries.timedeltas.to_timedelta(16, unit='h')

However I get this:

但是我得到了这个:

Out[2]: Timestamp('2010-03-11 00:00:00.000000016')

But I would like to get this:

但我想得到这个:

Out[2]: Timestamp('2010-03-11 16:00:00')

What I am missing?. The enviroment is Anaconda (latest) Python 2.7.7, iPython 2.2

我缺少什么?。环境是Anaconda(最新)Python 2.7.7,iPython 2.2

Thanks a lot

非常感谢

采纳答案by unutbu

You can use pd.DateOffset:

您可以使用pd.DateOffset

test[1].index + pd.DateOffset(hours=16)

pd.DateOffsetaccepts the same keyword arguments as dateutil.relativedelta.

pd.DateOffset接受与dateutil.relativedelta相同的关键字参数。



The problem you encountered was due to this bug which has been fixed in Pandas version 0.14.1:

您遇到的问题是由于此错误已在 Pandas 版本 0.14.1 中修复

In [242]: pd.to_timedelta(16, unit='h')
Out[242]: numpy.timedelta64(16,'ns')

If you upgrade, your original code should work.

如果您升级,您的原始代码应该可以工作。