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

标签 python pandas dataframe

这是我的数据框:

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)

我需要根据每列的增长率计算值(value) 我有一个包含 400 列及其相应增长率的数据框。

我使用以下公式计算了增长率:(一年前的值)*(1+当前月份的增长率)。此计算值将用于获取下一年的值等。像这样我有 400 列及其相应的增长率。时间序列有30年的数据

目前我使用 2 for 循环第一个获取每一列,然后第二个循环遍历每一列的时间段并获取在前一个 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])

最佳答案

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

希望对你有帮助

关于python - 基于增长率优化值的迭代计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880406/

相关文章:

python - 使用 Python 进行 SQL 注入(inject) (WordPress)

python - 如何在图像上绘制矢量场?

python - 如何按唯一值分组 pandas groupby

python - 如何在opencv python中调整PNG图像的大小?

python - Pandas 中的 Iterrows 合并会导致带有后缀的重复列

python - 如何将共现矩阵转换为 networkx 图

python - 从 Dask DataFrame 中删除列数不相等的行

python - 如何在 pandas df 中逐个单元地操作数据?

python - 根据python中的条件更新多个列值

R:用子字符串替换数据框的行名[2]