简体   繁体   English

如何在Python中执行向量化运算?

[英]How to perform vectorized operations in Python?

I'm having an issue with my simple code that is suppose to be a mortgage calculator where all the rates from 0.03 to 0.18 are listed in a table. 我的简单代码有一个问题,它可能是抵押计算器,其中所有利率从0.03到0.18都列在了表中。 Here is my code and error. 这是我的代码和错误。

l = 350000 #Loan amount
n = 30 #number of years for the loan
r = [0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18] #interest rate in decimal

n = n * 12
a = l
int1 = 12
u = [x / int1 for x in r]

D = (((u+1)**n)-1) /(u*(u+1)**n)

z = (a / D)
print(z)

File "test.py", line 23, in <module>
    D = (((u+1)**n)-1) /(u*(u+1)**n)
TypeError: can only concatenate list (not "int") to list

Thanks 谢谢

The problem is that u is a list which cannot be used for vectorized operation which you are doing while computing D . 问题是u是一个列表,不能用于计算D正在执行的矢量化操作。 You can convert your list to a NumPy array to make your code work. 您可以将列表转换为NumPy数组,以使代码正常工作。

u = np.array([x / int1 for x in r])

Alternatively, you can use a for loop or list comprehension to store D for each element of u as 另外,您可以使用for循环或列表推导将u每个元素的D存储为

D = [(((i+1)**n)-1) /(i*(i+1)**n) for i in u]

but this will again complain during z = (a / D) because D is still a list. 但这将在z = (a / D)期间再次抱怨,因为D仍然是列表。 Therefore, converting to array seems to be a convenient approach. 因此,转换为数组似乎是一种方便的方法。

The another alternative answer is to compute z using list comprehension directly without involving extra variable D 另一个替代答案是直接使用列表推导来计算z而不涉及额外的变量D

z = [a / (((i+1)**n)-1) /(i*(i+1)**n) for i in u]

The current error you're facing is because u is a list (made via a list comprehension ), and D tries to perform math operations between u (a list) and numbers. 您面临的当前错误是因为u是一个列表(通过list comprehension生成 ),而D尝试在u(一个列表)和数字之间执行数学运算。 That won't work. 那行不通。

Try this: 尝试这个:

import numpy as np
u = np.array([x / int1 for x in r])

u will be a NumPy array , which allows you to do vector math with it. 你将是一个NumPy数组 ,它允许你用它做向量数学。 If you've never used the numpy module, it's an easy install using the pip package manager. 如果您从未使用过numpy模块,则可以使用pip软件包管理器轻松安装。 If it's not installed then 如果未安装,则

import numpy as np

will throw an error, and you will not be able to use a NumPy array. 会引发错误,并且您将无法使用NumPy数组。 If you find yourself doing similar work often, it's likely worth the installation. 如果您发现自己经常做类似的工作,则可能值得安装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM