'Read .csv file and make all values float

I have a .csv file that contains only rows with cashflows in different lengths. I have a function that calculates the cashflow's NPVs, and all I have left is to calculate NPVs for all rows in the dataframe. However, running the code only returns "NaN" and I couldn't find out why.

I assume 2 problems could arise from my code:

  1. It wasn't imported as float values
  2. It wasn't able to deal with different lengths of cashflows.

Code:

import math
import pandas as pd
    
df = pd.read_csv('cashflowT1.csv',index_col=0)
e = math.e
r = 0.1
    
# function to calculate NPV with continous compunding
def npv(cashflow, r):
   '''calculate NPV with continous compunding'''
   a = []
   for i in range(len(cashflow)):
      a.append(float(cashflow[i]) * e**((-r)*i))
   return sum(a)
   
print(npv(df.iloc[0],r))


# what I wish my dataframe looked like after csv reading:
# df = [[-500,100,500,200,10],
#     [300,400,500,600,700],
#     [-12000,3500,3500,3500,3500,3500,3500,3500,3500,3500]]

# what I wish happened:
# (-500)*e**(-0.1)*1 + 100*e**(-0.1)*2 + 500*e**(-0.1)*3 ...


Solution 1:[1]

def npv(cashflow, r):
  '''calculate NPV with continous compunding'''
  a = []
  for i in range(len(cashflow)):
    a.append(float(cashflow[i]) * e**((-r)*i))
  return a

might get you a step closer.

this will return lists, which you then need to write to your dataframe (instead of print())

df['new'] = [npv(row,r) for row in df.itertuples()]

will write the output a to a new column in your dataframe

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1