首页 > 解决方案 > Python For 循环遍历范围

问题描述

我创建了一个类来计算贷款本金和利息。但是,我不知道为什么,但是我的 python 代码从第 2 个月开始计算值,而不是 1。所有值都是正确的,除了它将第 1 个月的值设置为 0 值。我不明白我做错了什么,我试图将范围更改为for t in range(0, len(self.data['month']+1)),python 显示错误:ValueError: array length 90361 does not match index length 90360.。这是我的代码:

class Collat: 


  def __init__(self, filename, collateral_activity, Pif_Prn = 0, Pif_Int=0):
    self.filename=filename
    self.data=self.data[['month','loan_number','p_prepay','loan_type','current_upb','current_interest_rate', 'DQ']]
    self.collateral_activity = collateral_activity
    self.month=self.data['month'].tolist()
    self.p_cure= self.data['p_prepay'].tolist()
    self.upb=self.data['current_upb'].tolist()
    self.int_r=self.data['current_interest_rate'].tolist()
    self.type= self.data['loan_type'].tolist()
    self.dq=self.data['DQ'].tolist()
    self.Pif_Prn= [Pif_Prn]
    self.Pif_Int = [Pif_Int]
   
    
    


    
  def calint(self, t):
    return  self.int_r[t]/12 *(self.month[t]+self.dq[t]+1)
    


  def generate(self):
    for t in range(1, len(self.data['month']+1)):
        self.Pif_Prn.append(self.p_prepay[t] * self.upb[t] )
        self.Pif_Int.append(self.Pif_Prn[t]* self.calint(t))
        
    
    lists= {'Prepaid Principal':self.Pif_Prn, 'Prepaid Int':self.Pif_Int }
    loan_activity = pd.DataFrame(lists)
    loan_activity.to_csv(self.collateral_activity, header=True, index=False)

输出如下所示:跳过第 1 个月的计算:

month  Prepaid Principal    Prepaid Interest
  1       0                     0
  2       55685                2546          

标签: pythonloops

解决方案


def generate看起来你写1而不是在0 python 中,列表索引从 开始0,所以会跳过第一个元素

def generate(self):
    for t in range(0, len(self.data['month']+1)):
                 # ^ Previously 1
      

推荐阅读