Home > Mobile >  How to use np.prod to rewrite python for loop function
How to use np.prod to rewrite python for loop function

Time:10-06

I am using pandas and numpy to deal with data, and I have a python function:

mt= np.array([1,2,3,4,5,6,7])

def getnpx(mt, age, interest):
    val = 1
    initval = 1
    for i in range(age, 6):
        val = val * mt[i]
        intval = val / (1   interest) ** (i   1 - age)
        initval = initval   intval
    return initval

If directly use pd.apply(getnpx),it will be very slow since the data size is very large ,so I want to convert this function into numpy,I think I maybe can use np.prod to rewrite it,but have no idea how to continue,since this function is very complicated!

Any friend can help?

CodePudding user response:

You don't want np.prod, you want np.cumprod:

def getnpx_(mt, age, interest):
    return 1   (np.cumprod(mt[age:6]) / (1 interest)**np.arange(1,(7-age))).sum()

age, interest = 3, 0.5
print(np.isclose(getnpx(mt, age, interest), getnpx_(mt, age, interest) ))
  • Related