如何使用pandas.date_range()获取指定的开始和结束日期之间n个指定周期(相等)的时间序列 [英] How can I use pandas.date_range() to obtain a time series with n specified periods (equal) between a specified start and end date

查看:1672
本文介绍了如何使用pandas.date_range()获取指定的开始和结束日期之间n个指定周期(相等)的时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在开始和结束日期(包括边界)之间列出一系列n个日期,但

I'd like to get a list or series of n dates between a start and end date (inclusive of those bounds), but

dateIndex=pd.date_range(start=dt.datetime.today().date(), end=pd.to_datetime(expiry).date(), periods=n)

带有ValueError的结果:必须指定开始,结束或句点两个。我不能使用freq = Freq参数,因为我的日期范围不统一 - 它可能是从一个月到两年的任何地方,因此我想要一个等距的n个点的时间序列。

results with ValueError: Must specify two of start, end, or periods. I cannot use freq=Freq argument because my date range won't be uniform - it may be anywhere from a month to 2 years span, thus I'd like an equally spaced time series with n points.

谢谢!

推荐答案

我不认为你只能用 date_range ,但是为什么不使用numpy的 linspace

I don't think you can do this just with date_range, but why not use numpy's linspace:

In [11]: start = pd.Timestamp('2012-01-01')

In [12]: end = pd.Timestamp('2012-02-01')

In [13]: np.linspace(start.value, end.value, 10)  # 10 dates inclusive
Out[13]:
array([  1.32537600e+18,   1.32567360e+18,   1.32597120e+18,
         1.32626880e+18,   1.32656640e+18,   1.32686400e+18,
         1.32716160e+18,   1.32745920e+18,   1.32775680e+18,
         1.32805440e+18])

In [14]: pd.to_datetime(np.linspace(start.value, end.value, 10))
Out[14]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-01 00:00:00, ..., 2012-02-01 00:00:00]
Length: 10, Freq: None, Timezone: None






您可以将此作为频率但是,对于不均匀分配的时间,这可能会/不准确:


You could pass this as a freq, but this may/will be inaccurate for times which don't evenly divide:

In [21]: (end - start)/ 9
Out[21]: datetime.timedelta(3, 38400)

In [22]: ((end - start)/ 9).total_seconds()
Out[22]: 297600.0

# Note: perhaps there's a better way to pass this as a freq?
In [23]: pd.date_range(start=start, end=end, freq='%iS' % ((end - start)/ 9).total_seconds())
Out[23]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-01 00:00:00, ..., 2012-02-01 00:00:00]
Length: 10, Freq: 297600S, Timezone: None

这篇关于如何使用pandas.date_range()获取指定的开始和结束日期之间n个指定周期(相等)的时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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