[英]Pandas Panel Data - Lagging variables by taking into consideration the year gap
[英]Pandas Panel Data - Shifting values by two taking into consideration year gaps
我目前正在处理有关 pandas 的财务信息面板数据,因此与不同年份的不同公司合作。 我正在尝试生成一个按 2 个时间段移动的 $ 投资列。 因此,也在 t+2 报告时间 t 的值。
通常,为了滞后一个变量,我会使用df.groupby('tic')['investments'].shift(2)
,但不幸的是我的数据有点参差不齐,因此对于同一家公司,我可能在年。 只是给你一个想法,这是我的 df 的一个例子:
datadate fyear tic invest
0 31/12/1998 1997 AAPL 12.3
1 31/12/1999 1998 AAPL 14.5
2 31/12/2002 2002 AAPL 9.7
3 31/12/2003 2003 AAPL 21.8
4 31/12/2004 2004 AAPL 21.4
5 31/12/2005 2005 AAPL 18.9
6 31/05/2008 2008 TSLA 11.5
7 31/05/2009 2009 TSLA 13.7
8 31/05/2010 2010 TSLA 19.4
9 31/05/2011 2011 TSLA 14.5
10 31/05/2014 2013 TSLA 14.8
.. ... .. .. ..
因此,我想要实现的目标如下:
datadate fyear tic invest l2_invest
0 31/12/1998 1997 AAPL 12.3 NaN
1 31/12/1999 1998 AAPL 14.5 NaN
2 31/12/2002 2002 AAPL 9.7 NaN
3 31/12/2003 2003 AAPL 21.8 NaN
4 31/12/2004 2004 AAPL 21.4 9.7
5 31/12/2005 2005 AAPL 18.9 21.8
6 31/05/2008 2008 TSLA 11.5 NaN
7 31/05/2009 2009 TSLA 13.7 NaN
8 31/05/2010 2010 TSLA 19.4 11.5
9 31/05/2011 2011 TSLA 14.5 13.7
10 31/05/2014 2013 TSLA 14.8 19.4
.. ... .. .. ..
预先感谢您的帮助:)
如果 'datadate' 列是表的索引(并且类型为 datetime64),则以下代码应生成所需的附加列:
df.groupby('tic')['invest'].shift(1, freq=pd.DateOffset(years=2))
编辑:仍然需要将 append 这个新列添加到原始表中。 这里有更多细节。
首先,确保“datadate”列的类型为 datetime64:
df['datadate'] = pd.to_datetime(df['datadate'])
然后让我们创建新列并将 append 它添加到我们的表中:
new_column = (df.set_index('datadate')
.groupby('tic')['invest']
.shift(1, freq=pd.DateOffset(years=2)))
df.set_index(['tic', 'datadate'], inplace=True)
df['l2_invest'] = new_column
df.reset_index(inplace=True)
从原始表开始,这会产生
tic datadate fyear invest l2_invest
0 AAPL 1998-12-31 1997 12.3 NaN
1 AAPL 1999-12-31 1998 14.5 NaN
2 AAPL 2002-12-31 2002 9.7 NaN
3 AAPL 2003-12-31 2003 21.8 NaN
4 AAPL 2004-12-31 2004 21.4 9.7
5 AAPL 2005-12-31 2005 18.9 21.8
6 TSLA 2008-05-31 2008 11.5 NaN
7 TSLA 2009-05-31 2009 13.7 NaN
8 TSLA 2010-05-31 2010 19.4 11.5
9 TSLA 2011-05-31 2011 14.5 13.7
10 TSLA 2014-05-31 2013 14.8 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.