Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 扩展日期范围_Python_Pandas - Fatal编程技术网

Python 扩展日期范围

Python 扩展日期范围,python,pandas,Python,Pandas,我有这样的数据。每行表示某个日期该ID的值 ID Date Value A 2012-01-05 50 A 2012-01-08 100 A 2012-01-10 200 B 2012-07-01 10 B 2012-07-03 20 我需要扩展它,这样我就有了所有天的行。每天的值应为前一天的值(即,将上面的数据视为值的更新,将下面的数据视为值的时间序列) 目前,我有一个相当于以下内容的解决方案: 按ID分组 对于每个组,

我有这样的数据。每行表示某个日期该ID的值

ID   Date         Value
A    2012-01-05   50
A    2012-01-08   100
A    2012-01-10   200
B    2012-07-01   10
B    2012-07-03   20
我需要扩展它,这样我就有了所有天的行。每天的值应为前一天的值(即,将上面的数据视为值的更新,将下面的数据视为值的时间序列)

目前,我有一个相当于以下内容的解决方案:

  • 按ID分组
  • 对于每个组,计算最小和最大日期
  • 创建pd.date\u范围
  • 同时遍历行和日期范围,填充日期范围中的值,并在必要时增加指向行的索引指针
  • 将所有这些日期范围附加到最终的数据帧
这是可行的,但似乎是一个相当糟糕的暴力解决方案。我想知道Pandas是否支持更好的方法?

Date
上使用带
ID
组的索引数据帧,在
值上使用
ffill

In [1725]: df.set_index('Date').groupby('ID').resample('1D')['Value'].ffill().reset_index()
Out[1725]:
  ID       Date  Value
0  A 2012-01-05     50
1  A 2012-01-06     50
2  A 2012-01-07     50
3  A 2012-01-08    100
4  A 2012-01-09    100
5  A 2012-01-10    200
6  B 2012-07-01     10
7  B 2012-07-02     10
8  B 2012-07-03     20
或者你可以试试这个(注意:这个也可以用于支出数字列)


类似但不完全相同。哦,哇,一行!1D是否指1天?如果我有相同类型的数据,但想要月初日期怎么办?是的,在Hmm检查别名这与OP中的输出不匹配?
In [1725]: df.set_index('Date').groupby('ID').resample('1D')['Value'].ffill().reset_index()
Out[1725]:
  ID       Date  Value
0  A 2012-01-05     50
1  A 2012-01-06     50
2  A 2012-01-07     50
3  A 2012-01-08    100
4  A 2012-01-09    100
5  A 2012-01-10    200
6  B 2012-07-01     10
7  B 2012-07-02     10
8  B 2012-07-03     20
df.Date=pd.to_datetime(df.Date)
df=df.set_index(df.Date)
df.set_index(df.Date).groupby('ID')\
   .apply(lambda x : x.reindex(pd.date_range(min(x.index), max(x.index),freq='D')))\
     .ffill().reset_index(drop=True)

Out[519]: 
  ID       Date  Value
0  A 2012-01-05   50.0
1  A 2012-01-05   50.0
2  A 2012-01-05   50.0
3  A 2012-01-08  100.0
4  A 2012-01-08  100.0
5  A 2012-01-10  200.0
6  B 2012-07-01   10.0
7  B 2012-07-01   10.0
8  B 2012-07-03   20.0