【发布时间】:2021-11-26 01:20:51
【问题描述】:
我有两个 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])
【问题讨论】:
-
您介意添加预期的输出吗?
pandas是怎么参与进来的? -
嗨@rpanai 谢谢你的回复我已经更新了我的问题请检查!
-
135需要硬编码吗?
-
是的,但是 135 可以小到 7
-
仅供参考:彻底回答问题非常耗时。 如果您的问题得到解决,请通过接受最适合您的需求的解决方案表示感谢。 接受检查位于答案左上角的向上/向下箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。您还可以使用向上或向下箭头对答案的质量/有用性进行投票。 如果解决方案不能回答问题,请发表评论。 What should I do when someone answers my question?。谢谢
标签: python numpy vectorization numpy-ndarray