简体   繁体   English

将日期插入DataFrame的行

[英]Inserting Dates into Rows of DataFrame

I have a DataFrame df whose index consist of Datetimes of each day in January for the years 1997 through 2011: 我有一个DataFrame df其索引包含1997年到2011年1月份每天的日期时间:

In [164]: df
Out[164]: 
             Tavg
1997-01-01  20.48
1997-01-02  37.49
...           ...
1997-01-31  37.49
1998-01-01  52.07
...           ...
2011-01-30  35.51
2011-01-31  29.03

From another DataFrame, I'd like to insert rows to df corresponding to Dec 31 of the previous year for each year; 从另一个DataFrame,我想在每年对应于上一年12月31日的df插入行; ie, rows with index 即具有索引的行

In [166]: prev_dates = pd.date_range('1996-12-31', '2010-12-31', freq=pd.DateOffset(years=1))

In [167]: prev_dates
Out[167]: 
DatetimeIndex(['1996-12-31', '1997-12-31', '1998-12-31', '1999-12-31',
               '2000-12-31', '2001-12-31', '2002-12-31', '2003-12-31',
               '2004-12-31', '2005-12-31', '2006-12-31', '2007-12-31',
               '2008-12-31', '2009-12-31', '2010-12-31'],
              dtype='datetime64[ns]', freq='<DateOffset: kwds={'years': 1}>')

After inserting the values from these rows, I'd like the new df to look like 从这些行插入值后,我希望新的df看起来像

             Tavg
1996-12-31  <new value>
1997-01-01  20.48
1997-01-02  37.49
...           ...
1997-01-31  37.49
1997-12-31  <new value>
1998-01-01  52.07
...           ...
2011-01-30  35.51
2011-01-31  29.03

but I can't seem to find the right methods to achieve this. 但我似乎无法找到正确的方法来实现这一目标。

reindex with union union reindex结合

df.reindex(prev_dates.union(df.index))

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM