You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas DataFrame迭代计算现金流,替代变量列表法

问题描述

当前通过逐个定义变量存储每年现金流、再将变量值存入列表后导入DataFrame的方式计算折现现金流,希望改用Pandas原生方法,直接通过DataFrame复用前一行数据完成计算,替代冗余的变量与列表操作。

原实现代码:

import math
import pandas as pd

# User input
cashflow = 3.6667
fcf_growth_for_first_5_years = 14/100
fcf_growth_for_last_5_years = 7/100
no_of_years = 10
t_g_r = 3.50/100 ## Terminal Growth Rate
discount_rate = 10/100

## fcf calculaton for 10 Years
future_cash_1_year = cashflow*(1+fcf_growth_for_first_5_years)
future_cash_2_year = future_cash_1_year*(1+fcf_growth_for_first_5_years)
future_cash_3_year = future_cash_2_year*(1+fcf_growth_for_first_5_years)
future_cash_4_year = future_cash_3_year*(1+fcf_growth_for_first_5_years)
future_cash_5_year = future_cash_4_year*(1+fcf_growth_for_first_5_years)
future_cash_6_year = future_cash_5_year*(1+fcf_growth_for_last_5_years)
future_cash_7_year = future_cash_6_year*(1+fcf_growth_for_last_5_years)
future_cash_8_year = future_cash_7_year*(1+fcf_growth_for_last_5_years)
future_cash_9_year = future_cash_8_year*(1+fcf_growth_for_last_5_years)
future_cash_10_year = future_cash_9_year*(1+fcf_growth_for_last_5_years)

fcf = []
fcf.extend(value for name, value in locals().items() if name.startswith('future_cash_'))

cf = pd.DataFrame()
cf.insert(0, 'Sr_No', range(1,11))
cf.insert(1, 'Year', range(23,33))
cf['fcf'] = fcf
cf

目标输出:

Sr_No Year    fcf
0     1   23  4.180038
1     2   24  4.765243
2     3   25  5.432377
3     4   26  6.192910
4     5   27  7.059918
5     6   28  7.554112
6     7   29  8.082900
7     8   30  8.648703
8     9   31  9.254112
9    10  32  9.901900

高效实现方案

利用Pandas的向量化运算与累积乘积方法,直接在DataFrame内完成现金流计算,无需额外变量与列表:

import pandas as pd

# User input
cashflow = 3.6667
fcf_growth_for_first_5_years = 14/100
fcf_growth_for_last_5_years = 7/100
no_of_years = 10
t_g_r = 3.50/100 ## Terminal Growth Rate
discount_rate = 10/100

# 初始化DataFrame,构建Sr_No与Year列
cf = pd.DataFrame({
    'Sr_No': range(1, no_of_years + 1),
    'Year': range(23, 23 + no_of_years)
})

# 生成对应年份的增长率序列:前5年用14%,后5年用7%
cf['growth_rate'] = [fcf_growth_for_first_5_years]*5 + [fcf_growth_for_last_5_years]*5

# 计算每年现金流:初始现金流 × (1+增长率)的累积乘积
cf['fcf'] = cashflow * (1 + cf['growth_rate']).cumprod()

# 可选:如果不需要保留growth_rate列,可以删除
# cf = cf.drop('growth_rate', axis=1)

print(cf.round(6))

方案优势

  • 代码简洁易维护:无需逐个定义年份变量,调整年份数或增长率时只需修改参数
  • 原生Pandas操作:利用向量化运算替代循环/手动变量赋值,计算效率更高
  • 逻辑清晰:直接在DataFrame内完成所有计算,数据流转更直观

内容的提问来源于stack exchange,提问作者Divyank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:15:46