0

I have the following dataframe:

import numpy as np
import pandas as pd
dates = pd.date_range(start='2014-01-01',end='2018-01-01',  freq='Y')
df = pd.DataFrame(5*np.eye(4,), index=dates, columns=['Var1', 'Var2', 'Var3', 'Var4'])
print(df)

            Var1  Var2  Var3  Var4
2014-12-31   5.0   0.0   0.0   0.0
2015-12-31   0.0   5.0   0.0   0.0
2016-12-31   0.0   0.0   5.0   0.0
2017-12-31   0.0   0.0   0.0   5.0

I would like to compute the NPV value of each variable for the years 2014 and 2015 for 3 years.

Right now I know how to obtain the present value for one variable and one row at the time:

Var1_2014     = df.loc['2014':'2016','Var1'].tolist()
NPV_Var1_2014 = np.npv(0.7,[0]+Var1_2014) 

However I do not know how to vectorize the function to compute directly the entire column. I would like to obtain something like that:

             Var1  Var2  Var3  Var4  Var1_NPV
2014-12-31   5.0   0.0   0.0   0.0      a
2015-12-31   0.0   5.0   0.0   0.0      b
2016-12-31   0.0   0.0   5.0   0.0     Nan
2017-12-31   0.0   0.0   0.0   5.0     Nan

where I could say something like df['Var1_NPV']= npv('Var1',duration=3years,discount_rate=0.7)

Any idea on how I could vectorize that function efficiently?

Many thanks,

Peslier53
  • 587
  • 1
  • 7
  • 21
  • Possible duplicate of [Call apply-like function on each row of dataframe with multiple arguments from each row](https://stackoverflow.com/questions/15059076/call-apply-like-function-on-each-row-of-dataframe-with-multiple-arguments-from-e) – programmar Oct 20 '18 at 15:33
  • @programmar I am not using R. But thank you for your help – Peslier53 Oct 20 '18 at 15:35

1 Answers1

0

I find a solution with apply and offset:

def give_npv(date,df,var,wacc):   
    date2 = date + pd.DateOffset(years=2)  
    data    = df.loc[date:date2,var].tolist()
    NPV_var = np.npv(wacc,[0]+data) 
    return NPV_var


df['index2'] = df.index
df['test'] = df.apply(lambda x: give_npv(x['index2'],df,'Var2',0.07) ,axis=1 ) 
print(df)

            Var1  Var2  Var3  Var4     index2      test
2014-12-31   5.0   0.0   0.0   0.0 2014-12-31  4.367194
2015-12-31   0.0   5.0   0.0   0.0 2015-12-31  4.672897
2016-12-31   0.0   0.0   5.0   0.0 2016-12-31  0.000000
2017-12-31   0.0   0.0   0.0   5.0 2017-12-31  0.000000
Peslier53
  • 587
  • 1
  • 7
  • 21