我很难为以下问题创建一个矢量化的解决方案:
bp sp pct_growth
0 1.0 2.0 100.0
1 1.0 1.5 50.0
2 1.0 2.0 100.0我需要根据初始数量(假设1000)计算绝对累积增长:
bp sp pct_growth abs_growth
0 1.0 2.0 100.0 2000.0
1 1.0 1.5 50.0 3000.0
2 1.0 2.0 100.0 6000.0下面的代码可以工作,但是我想找到一个矢量化的解决方案:
a = [{'bp': 1.0, 'sp': 2}, {'bp': 1.0, 'sp': 1.5}, {'bp': 1.0, 'sp': 2}]
df2 = pd.DataFrame(a)
df2['pct_growth'] = df2[['bp','sp']].pct_change(axis=1)['sp'] * 100
for index, row in df2.iterrows():
if index == 0:
df2.loc[index, 'abs_growth'] = 1000 + 1000*row['pct_growth']/100
else:
df2.loc[index, 'abs_growth'] = df2.loc[index-1, 'abs_growth'] + df2.loc[index-1, 'abs_growth']*row['pct_growth']/100发布于 2022-10-02 00:39:21
您可以通过(1 + df.pct_growth / 100).cumprod()计算绝对增长率,然后再乘以逻辑定义的base:
base = 1000
df['abs_growth'] = (1 + df.pct_growth / 100).cumprod() * base
df
bp sp pct_growth abs_growth
0 1.0 2.0 100.0 2000.0
1 1.0 1.5 50.0 3000.0
2 1.0 2.0 100.0 6000.0https://stackoverflow.com/questions/73922633
复制相似问题