Python Pandas,有没有办法将date_range拆分成大小相等的间隔?

时间:2015-02-13 16:08:00

标签: python pandas time-series

我目前正在使用Python(Pandas模块)开发一个项目。我想要做的是将date_range分成相等大小的间隔。

import pandas as pd
startdate='2014-08-08'
enddate='2014-08-11'
n=3
pd.date_range(start=startdate,end=enddate)

我想要的是将中间日期作为字符串返回的某种方式,例如:

startdate='2014-08-08'
intermediate_1='2014-08-09'
intermediate_2='2014-08-10'
enddate='2014-08-11'

这是几天的例子,但我希望能够在数小时或数分钟内完成同样的工作。有没有办法在当前的Pandas模块中执行此操作?任何帮助将不胜感激。

此致 亚历

1 个答案:

答案 0 :(得分:0)

您可以使用np.split拆分数组,这会返回一个datetimeindex值数组,因此我们必须使用[0]访问value元素,然后我们可以调用属性date()并且施展到str:

In [238]:

startdate='2014-08-08'
enddate='2014-08-11'
n=3
d = pd.date_range(start=startdate,end=enddate)
d
Out[238]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-08-08, ..., 2014-08-11]
Length: 4, Freq: D, Timezone: None
In [249]:
# split to produce n-1 blocks
splits = np.split(d, n-1)
# show the contents
for t in splits:
    print(t)
# assign each element, then access the value using [0] and access the date attribute and cast to str
intermediate_1 = str(splits[0][0].date())
intermediate_2 = str(splits[-1][0].date())
# show intermediate_1 which shows it is a str representation of the date
intermediate_1
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-08-08, 2014-08-09]
Length: 2, Freq: D, Timezone: None
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-08-10, 2014-08-11]
Length: 2, Freq: D, Timezone: None
Out[249]:
'2014-08-08'
相关问题