You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码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分支的触发条件,但代码始终未进入该分支。尝试调整分支顺序、显式调用字段等操作,问题仍未解决。

预期输出

loannumprinbalprinamtintamtintbal
1113038254.503038254.50132664.98132664.98
2224547685.234547685.23198574.08198574.08

内容的提问来源于stack exchange,提问作者gernworm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 16:13:19