2016-11-30 47 views
6

这是我的数据框:优化值的迭代计算基础上的增长速度

Date    A   new_growth_rate 
2011/01/01  100    
2011/02/01  101    
. 
2012/01/01  120   0.035 
2012/02/01  121   0.035 
. 
2013/01/01  131   0.036 
2013/01/01  133   0.038 

这就是我需要:

Date    A   new_growth_rate 
2011/01/01  100    
2011/02/01  101    
. 
. 
2012/01/01  103.62   .035 A=100/(1-0.035) 
2012/02/01  104.66   .035 A=101/(1-0.035) 
. 
. 
2013/01/01  107.49   .036 A=103.62/(1-0.036) 
2013/02/01  108.68   .038 A=104.66/(1-0.038) 

我需要基于增长速度为每列 来计算值我有一个400列的数据框和相应的增长率。

我已经使用以下公式计算增长率:(one year old value)*(1+current month growth rate)。这个计算的值将用于获取下一年的价值等等。像这样我有400列和他们相应的增长率。时间序列具有30年的数据

当前我正在使用2 for循环一来获取每列,然后第二遍迭代每列的时间段,并获得前一个for循环计算的值。需要几个小时才能查看500行和400列数据集。对此有一个更好的办法`

我的代码片段如下:?

grpby =在数据帧名单之列

df_new=pd.DataFrame() 
for i,row in grpby.iterrows(): 
    df_csr=grwth.loc[(grwth['A']==row['A'])].copy() 
     a = pd.to_datetime("2011-12-01",format='%Y-%m-%d') 
     b = a 
     while b <a+relativedelta.relativedelta(months=420): 
      b=b+relativedelta.relativedelta(months=1) 
      val= df_csr.loc[df_csr['Date']==(b+relativedelta.relativedelta(months=-12))].copy() 
      val2=val.get_value(val.index[0],'Val') 
      grwth_r=df_csr.loc[df_csr['date']==b]['new_growth_rate'].copy() 
      grwth_r2=grwth_r.get_value(grwth_r.index[0],'new_growth_rate') 
      df_csr.loc[df_csr['Date']==b,'Val']=val2/(1-grwth_r2) 
     df_new=pd.concat([df_new,df_csr]) 
+4

请包括[MCVE(http://stackoverflow.com/help/mcve)(什么是'grwth')给我们提供了足够的数据一起玩,但没有更多的 –

+0

看对于series.rolling.apply –

+0

GRWTH是列表 – Sanjay

回答

1

可以使用一年的值作为索引,然后使用简单的for循环来分配数据,即

df['Date'] = pd.to_datetime(df['Date']) 
df = df.set_index('Date') 
years = (df.index.year).unique() 

for i,j in enumerate(years): 
    if i != 0: 
     prev = df.loc[df.index.year == years[i-1]] 
     curr = df.loc[df.index.year == j] 
     df.loc[df.index.year == j,'A'] = prev['A'].values/(1-curr['new_growth_rate'].values) 

输出:

 
        A new_growth_rate 
Date         
2011-01-01 100.000000    NaN 
2011-02-01 101.000000    NaN 
2012-01-01 103.626943   0.035 
2012-02-01 104.663212   0.035 
2013-01-01 107.496829   0.036 
2013-01-01 108.797518   0.038 

希望它可以帮助