【问题标题】:Optimising iterative computation of values based on growth rate基于增长率优化值的迭代计算
【发布时间】:2017-04-14 07:21:18
【问题描述】:

这是我的数据框:

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 列的数据框及其相应的增长率。​​p>

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

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

我的代码 sn-p 如下:

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])

【问题讨论】:

  • 请附上mcve:只给我们足够的数据来玩,但不要更多(grwth 是什么?)
  • 寻找 series.rolling.apply
  • GRWTH 是列列表
  • df['A'].shift(12) / ( 1.0 - df['new_growth_rate'] )

标签: python pandas dataframe


【解决方案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)

输出:

一个新的增长速率 日期 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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多