代码if分支未匹配预期逻辑,prinbal/prinamt出现异常负值
贷款计算中prinbal/prinamt字段出现意外负值,未匹配预期分支
示例DataFrame代码
import pandas as pd import numpy_financial as npf from datetime import datetime as dt from dateutil.relativedelta import relativedelta df = pd.DataFrame({ 'loannum': [111, 222], 'datadt': [dt.datetime(2024, 2, 29), dt.datetime(2024, 2, 29)], 'balloondt_i': [dt.datetime(2024, 8, 1), dt.datetime(2024, 8, 1)], 'balloondt': [dt.datetime(2024, 8, 1), dt.datetime(2024, 8, 1)], 'currbal': [21662536.64, 32424669.41], 'rate': [7.349, 7.349], 'pmtfreq': [1, 1], 'int_only': [None, None], 'dpd_mult': [1, 1], 'prinbal': [0, 0], 'prinamt': [0, 0], 'pmtamt': [34669, 51893], 'intamt': [0, 0], 'intbal': [0, 0] })
运行代码及异常情况
执行以下代码后,prinbal和prinamt字段出现意外负值:贷款111的两个字段值为-97995.98,贷款222为-146681.08,而预期值应为贷款111的3038254.50、贷款222的4547685.23。
for idx in df.index: dpd_mult = df.loc[idx, 'dpd_mult'] datadt = df.loc[idx, 'datadt'] balloondt_i = df.loc[idx, 'balloondt_i'] currbal = df.loc[idx, 'currbal'] rate = df.loc[idx, 'rate'] pmtfreq = df.loc[idx, 'pmtfreq'] pmtamt = df.loc[idx, 'pmtamt'] if not pd.isna(df.loc[idx, 'pmtamt']) else None int_only = df.loc[idx, 'int_only'] intbal = df.loc[idx, 'intbal'] if balloondt_i <= datadt + relativedelta(months=+1): # 模拟'intnx'逻辑 df.loc[idx, 'prinamt'] = df.loc[idx, 'currbal'] else: for i in range(dpd_mult): if currbal <= 0: # 余额为0或负时终止循环 break df.loc[idx, 'intbal'] = df.loc[idx, 'currbal'] * rate / 1200 * pmtfreq if int_only == 'IO': df.loc[idx, 'prinbal'] = 0 elif intbal >= pmtamt: nperiods = max(1, 12 * (balloondt_i.year - datadt.year) + (balloondt_i.month - datadt.month) - (i - 1) * pmtfreq) / pmtfreq df.loc[idx, 'prinbal'] = npf.pmt(rate * pmtfreq / 1200, nperiods, currbal) - intbal else: df.loc[idx, 'prinbal'] = df.loc[idx, 'pmtamt'] - df.loc[idx, 'intbal'] df.loc[idx, 'currbal'] -= df.loc[idx, 'prinbal'] df.loc[idx, 'prinamt'] += df.loc[idx, 'prinbal'] df.loc[idx, 'intamt'] += df.loc[idx, 'intbal']
排查情况
通过df.loc[df['intbal'] > df['pmtamt']]筛选可确认intbal计算正确,且符合elif分支的触发条件,但代码始终未进入该分支。尝试调整分支顺序、显式调用字段等操作,问题仍未解决。
预期输出
| loannum | prinbal | prinamt | intamt | intbal |
|---|---|---|---|---|
| 111 | 3038254.50 | 3038254.50 | 132664.98 | 132664.98 |
| 222 | 4547685.23 | 4547685.23 | 198574.08 | 198574.08 |
内容的提问来源于stack exchange,提问作者gernworm
相关产品推荐
相关产品推荐

