我是 Python 新手,正在尝试为 400 笔贷款列表生成摊销计划。最终结果仅包含每个月末的loan_id 和剩余余额,直到还清贷款。
我发现了一个关于摊销功能的帖子,需要帮助来了解如何循环浏览我的贷款清单。
我的贷款清单是这样的:
以下是我目前使用的代码:
def amortize(loan_id, principal, remaining_balance, interest_rate, years, annual_payments=12, start_date=date.today()):
pmt = -round(np.pmt(interest_rate/annual_payments, years*annual_payments, principal), 2)
# initialize the variables to keep track of the periods and running balances
p = 1
beg_balance = remaining_balance
end_balance = remaining_balance
while end_balance > 0:
# Recalculate the interest based on the current balance
interest = round(((interest_rate/annual_payments) * beg_balance), 2)
# Determine payment based on whether or not this period will pay off the loan
pmt = min(pmt, beg_balance + interest)
principal = pmt - interest
# Ensure additional payment gets adjusted if the loan is being paid off
end_balance = beg_balance - principal
yield OrderedDict([('Load ID', loan_id),
('Month',start_date),
('Period', p),
('Begin Balance', beg_balance),
('Payment', pmt),
('Principal', principal),
('Interest', interest),
('End Balance', end_balance)])
# Increment the counter, balance and date
p += 1
start_date += relativedelta(months=1)
beg_balance = end_balance
我只知道如何将 amortize 函数应用于选定的行,但如何将循环写入所有列表?(列表是我的贷款数据框的名称)
amo_schedule = pd.DataFrame(amortize(list['id'][0],
list['origination'][0],
list['remaining_balance'][0],
list['interest'][0]/100,
list['term'][0],
start_date=date(2020,11,1)))
删除索引时,我收到以下代码的错误消息。
test = pd.DataFrame(amortize(list['id'],
list['origination'],
list['remaining_balance'],
list['interest'],
list['term'],
start_date=date(2020,11,1)))
ValueError Traceback (most recent call last)
<ipython-input-314-11e01c7c284f> in <module>
----> 1 test = pd.DataFrame(amortize(list['id'],
2 list['origination'],
3 list['remaining_balance'],
4 list['interest'],
5 list['term'],
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
500 elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):
501 if not isinstance(data, (abc.Sequence, ExtensionArray)):
--> 502 data = list(data)
503 if len(data) > 0:
504 if is_dataclass(data[0]):
<ipython-input-281-f6ccf21b26cb> in amortize(loan_id, principal, remaining_balance, interest_rate, years, annual_payments, start_date)
7 end_balance = remaining_balance
8
----> 9 while end_balance > 0:
10
11 # Recalculate the interest based on the current balance
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1327
1328 def __nonzero__(self):
-> 1329 raise ValueError(
1330 f"The truth value of a {type(self).__name__} is ambiguous. "
1331 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().