Numpy如何使用np.umprod重写range函数中i的python

2022-03-16 00:00:00 python numpy numpy-ndarray vectorization

问题描述

我有两个python函数。第一个:

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

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

输出为:

48.111111111111114

为了加快速度,我使用Numpy对其进行了矢量化:

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

getnpx_(mt, age, interest)

运行正常,输出仍为:

48.111111111111114

但是,我不知道如何使用numpy重写我的第二个函数:

pt1 = np.array([1, 2, 3, 4, 5, 6, 7])
pt2 = np.array([2, 4, 3, 4, 7, 4, 8])
pvaltable = np.array([0, 0, 0, 0, 0, 0, 0])

def jointpval(pt1, pt2, age1, age2):
    j = age1
    for i in range(age2, 6):
        k = min(j, 135)
        pvaltable[i] = pt1[k] * pt2[i]
        j = j + 1
    return pvaltable

jointpval(pt1, pt2, 3, 4)

输出:

array([ 0,  0,  0,  0, 28, 20,  0])

我希望能够转换循环

for i in range(age2, 6):

为类似以下内容:

np.cumprod(pt1[age:6])

最终输出应与:

相同
array([ 0,  0,  0,  0, 28, 20,  0])

解决方案

我找到此解决方案:

import numpy as np
pt1 = np.array([1, 2, 3, 4, 5, 6, 7])
pt2 = np.array([2, 4, 3, 4, 7, 4, 8])

def jointpval(pt1, pt2, age1, age2):
    pvaltable = np.zeros(len(pt1))
    idx2 = np.arange(age2, 6)
    idx1 = np.arange(len(idx2)) + age1
    idx1 = np.where(idx1 > 135, 135, idx1) 
    pvaltable[idx2] = pt1[idx1] * pt2[idx2]
    return pvaltable

WHEREjointpval(pt1, pt2, 3, 4)返回

array([ 0.,  0.,  0.,  0., 28., 20.,  0.])

相关文章