Home > Enterprise >  USE the above row to calculate the value for below row iteratively using pandas dataframe
USE the above row to calculate the value for below row iteratively using pandas dataframe

Time:08-22

I want create dataframe by reusing the above row to calculate the value of below row. Currently I am using variables to stores values and creating list and pushing list to cf dataframe to calculate Discount Cash Flows.

Current Reproducible code-

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

Desired Output-

I am getting desired output by using lst method code as given above, but I am looking for more efficient way to calculate values using pandas df instead of using lst & variables.


  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

CodePudding user response:

Using a for loop makes this much more easier to handle

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

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

##fcf calculaton for 10 Years
fcf=[]
for row in range(len(cf)):
    if cf.Sr_No[row]==1:
        fcf.append(cashflow*(1 fcf_growth_for_first_5_years))
    elif cf.Sr_No[row]<6:
        fcf.append(fcf[row-1]*(1 fcf_growth_for_first_5_years))
    else:
        fcf.append(fcf[row-1]*(1 fcf_growth_for_last_5_years))
cf['fcf'] = fcf
cf
  • Related