基于增长率优化值的迭代计算

San*_*jay 6 python dataframe pandas

这是我的数据帧:

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
Run Code Online (Sandbox Code Playgroud)

这就是我需要的:

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)
Run Code Online (Sandbox Code Playgroud)

我需要根据每列的增长率计算价值我有一个400列的数据框及其相应的增长率.

我用以下公式计算了增长率:(one year old value)*(1+current month growth rate).此计算值将用于获取明年的值等等.像这样,我有400列及其相应的增长率.时间序列有30年的数据

目前我使用2 for循环1获取每列,然后第二次迭代每列的时间段并获得在之前for循环中计算的值.超过500行和400列数据集需要几个小时.还有更好的方法吗?`

我的代码段如下:

grpby = dataframe中的列列表

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])
Run Code Online (Sandbox Code Playgroud)

Flo*_*oor 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)
Run Code Online (Sandbox Code Playgroud)

输出 :

                    新增长率
日期                                   
2011-01-01 100.000000 南
2011-02-01 101.000000 南
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

希望能帮助到你