基于增长优化迭代计算值

2024-07-04 16:49:47 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据帧:

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循环1来获取每一列,然后第二次遍历每一列的时间段,并获取在前一个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])

Tags: 数据dfnewfordateratevalueloc
1条回答
网友
1楼 · 发布于 2024-07-04 16:49:47

您可以使用年份值作为索引,然后使用一个简单的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

希望有帮助

相关问题 更多 >

    热门问题