如何在Python中执行矢量化操作?

时间:2018-10-26 16:05:33

标签: python vectorization

我的简单代码有一个问题,该代码应该是抵押计算器,其中所有利率从0.03到0.18都列在一个表中。这是我的代码和错误。

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

谢谢

2 个答案:

答案 0 :(得分:3)

问题在于u是不能用于计算D的向量化操作的列表。您可以将列表转换为NumPy数组以使代码正常工作。

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

或者,您可以使用for循环或列表理解将D的每个元素的u存储为

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

,但这将在z = (a / D)期间再次抱怨,因为D仍然是列表。因此,转换为数组似乎是一种方便的方法。

另一种替代答案是直接使用列表推导来计算z,而无需涉及额外的变量D

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

答案 1 :(得分:3)

当前面临的错误是因为u是一个列表(通过list comprehension生成),D尝试在u(列表)和数字之间执行数学运算。那行不通。

尝试一下:

constructor(private http: HttpClient, private pwsNotificationService: PwsNotificationService) { }

  public createRuleRequest(rule: Rule, form: NgForm, dataRulesList: DataRulesListComponent) {
    //form logic
   this._postCreateRuleRequest(rule, form, dataRulesList)
  }

  private _postCreateRuleRequest(rule: Rule, form: NgForm, dataRulesList: DataRulesListComponent) {
    this.http.post(`${environment.API_URL}rules/create`, rule).subscribe((response: any) => {
      this.pwsNotificationService.add({
        type: 'success',
        msg: `Rule Created!`,
        timeout: 5000
      });
      rule.reset();
      form.reset();
      //tried calling list.updateHistory from here
    }, () => {
      this.pwsNotificationService.add({
        type: 'danger',
        msg: `POST Request Failed. Please contact the Data Monitoring Team.`,
        timeout: 5000
      });
    }//tried adding a .complete function here);
  }

u将是NumPy array,您可以使用它进行向量数学运算。如果您从未使用过numpy模块,则可以使用pip软件包管理器轻松进行安装。如果尚未安装

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

将引发错误,并且您将无法使用NumPy数组。如果您发现自己经常做类似的工作,则可能值得安装。