Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function to elements of dataframe

Suppose I have the following dataframe df

              1      3
Scenario1  0.001   0.05
Scenario2  0.003   0.01
Scenario3  0.001   0.042
Scenario4  0.09    0.006
Scenario5  0.02    0.04

Suppose these are interest rates and periods and I want to compute the annuity.

If you are not familiar with it think I just want to apply this formula:

    def computeAnnuity(r,n):
        return (1-(1+r)**-n)/r

How can I get a dataframe where for each element I have computed the value of the function before?

I would like to do something like

df.applymap(computeAnnuity)

giving as r the return (each element in the df) and as n the columns' name of the dataframe (that are 1 and 3). But I do not know how to do it in an efficient way without looping or doing for cycles.

In other words to give you a practical example for Scenario1 period 1 where there is 0.001 I want (1-(1+0.001)**-1)/0.001 or, for instance, for Scenario4 period 3 where I have 0.006 I want (1-(1+0.006)**-3)/0.006. I would like to do it for every element in the dataframe (in an efficient and automatic way: using the function).

like image 226
Thegamer23 Avatar asked May 16 '26 19:05

Thegamer23


1 Answers

I think you need apply:

def computeAnnuity(r,n):
    return (1-(1+r)**-n)/r

df1 = df.apply(lambda x: computeAnnuity(x, x.name))
print (df1)
                  1         3
Scenario1  0.999001  2.723248
Scenario2  0.997009  2.940985
Scenario3  0.999001  2.764591
Scenario4  0.917431  2.964357
Scenario5  0.980392  2.775091

print ((1-(1+0.001)**-1)/0.001)
0.9990009990008542
like image 175
jezrael Avatar answered May 19 '26 07:05

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!