将 pandas datetimeindex延长1个周期 [英] extend a pandas datetimeindex by 1 period

查看:168
本文介绍了将 pandas datetimeindex延长1个周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑DateTimeIndex dates

dates = pd.date_range('2016-01-29', periods=4, freq='BM')
dates

DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29'],
              dtype='datetime64[ns]', freq='BM')

我想以附加到对象的频率将索引延长一个周期.

I want to extend the index by one period at the frequency attached to the object.

我希望

pd.date_range('2016-01-29', periods=5, freq='BM')

DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
               '2016-05-31'],
              dtype='datetime64[ns]', freq='BM')


我尝试过


I've tried

dates.append(dates[[-1]] + pd.offsets.BusinessMonthEnd())

但是

  • 未普遍使用dates
  • 的频率
  • 我收到性能警告
  • Not generalized to use frequency of dates
  • I get a performance warning

PerformanceWarning:非向量化的DateOffset应用于Series或DatetimeIndex

PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex

推荐答案

DatetimeIndex中的时间戳已经知道它们描述的是工作月份结束,因此您只需添加1:

The timestamps in your DatetimeIndex already know that they are describing business month ends, so you can simply add 1:

import pandas as pd
dates = pd.date_range('2016-01-29', periods=4, freq='BM')

print(repr(dates[-1]))
# => Timestamp('2016-04-29 00:00:00', offset='BM')

print(repr(dates[-1] + 1))
# => Timestamp('2016-05-31 00:00:00', offset='BM')

您可以使用.union将后者添加到索引中:

You can add the latter to your index using .union:

dates = dates.union([dates[-1] + 1])
print(dates)
# => DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
#                   '2016-05-31'],
#                  dtype='datetime64[ns]', freq='BM')

.append相比,它保留了偏移量的知识.

Compared to .append, this retains knowledge of the offset.

这篇关于将 pandas datetimeindex延长1个周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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