在Pandas中将日期范围转换为时间序列

3

我的原始数据如下所示:

  start_date   end_date  value
0 2016-01-01 2016-01-03      2
1 2016-01-05 2016-01-08      4

这段话的意思是,在2016年1月1日至1月3日之间,数据取值为2,而在2016年1月5日至1月8日之间,数据取值为4。我想将原始数据转化为日时间序列,如下所示:

2016-01-01    2
2016-01-02    2
2016-01-03    2
2016-01-04    0
2016-01-05    4
2016-01-06    4
2016-01-07    4
2016-01-08    4

请注意,如果时间序列中的某个日期未出现在原始数据的任何行的start_dateend_date之间,则该日期在时间序列中将获得0的值。
我可以通过循环原始数据来创建时间序列,但是这样很慢。有没有更快的方法?

请检查您的预期输出或此条件:“如果原始数据中没有出现日期,则其值为0” - 为什么对于01、02、05、06、07这些日期,您有“values != 0”的限制? - MaxU - stand with Ukraine
抱歉造成困惑。希望修改后能更清晰明了。 - hahdawg
1个回答

2
你可以尝试这个方法:
In [120]: df
Out[120]:
  start_date   end_date  value
0 2016-01-01 2016-01-03      2
1 2016-01-05 2016-01-08      4

In [121]: new = pd.DataFrame({'dt': pd.date_range(df.start_date.min(), df.end_date.max())})

In [122]: new
Out[122]:
          dt
0 2016-01-01
1 2016-01-02
2 2016-01-03
3 2016-01-04
4 2016-01-05
5 2016-01-06
6 2016-01-07
7 2016-01-08

In [123]: new = new.merge(df, how='left', left_on='dt', right_on='start_date').fillna(method='pad')

In [124]: new
Out[124]:
          dt start_date   end_date  value
0 2016-01-01 2016-01-01 2016-01-03    2.0
1 2016-01-02 2016-01-01 2016-01-03    2.0
2 2016-01-03 2016-01-01 2016-01-03    2.0
3 2016-01-04 2016-01-01 2016-01-03    2.0
4 2016-01-05 2016-01-05 2016-01-08    4.0
5 2016-01-06 2016-01-05 2016-01-08    4.0
6 2016-01-07 2016-01-05 2016-01-08    4.0
7 2016-01-08 2016-01-05 2016-01-08    4.0

In [125]: new.ix[(new.dt < new.start_date) | (new.dt > new.end_date), 'value'] = 0

In [126]: new[['dt', 'value']]
Out[126]:
          dt  value
0 2016-01-01    2.0
1 2016-01-02    2.0
2 2016-01-03    2.0
3 2016-01-04    0.0
4 2016-01-05    4.0
5 2016-01-06    4.0
6 2016-01-07    4.0
7 2016-01-08    4.0

谢谢。这比我之前使用的循环快了几个数量级。 - hahdawg
@hahdawg,很高兴我能帮到你 :) - MaxU - stand with Ukraine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接