python - 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
解决方案
def generate
看起来你写1
而不是在0
python 中,列表索引从 开始0
,所以会跳过第一个元素
def generate(self):
for t in range(0, len(self.data['month']+1)):
# ^ Previously 1
推荐阅读
- python - python中switch语句的不同值的相同输出
- node.js - Typescript Express 请求打字
- python - 视频帧的Python序列化添加磁盘内存
- keyboard - 重新映射两个波浪号/摆动键之一以成为 Right-Shift 键
- javascript - 使用 JSQR 从图像中读取小 QR 码
- reactjs - 有没有办法通过单击按钮打开电子邮件客户端
- databricks - Databricks 始终自动启动
- shopify - 如何在 Shopify 上延迟加载图片?
- php - 在 PHP 中,有没有办法检测字符串是否包含任何单词?
- r - 如何清理闪亮的侧边栏 UI