使用while循环在python中复制数据行

时间:2019-12-10 19:27:37

标签: python pandas dataframe

这是我用来创建简单摊销表的代码。使用数据框,尽管它在我打印数据框时会复制列名:

import numpy
import pandas
homeprice = 500000
LoanAmt = 500000
term = 30
interestrate = 0.0325
i= 1
Interestonlyterm = 5
while i<=term:
if i <= Interestonlyterm:
    Payment = round(LoanAmt * interestrate / 12, 2)
    Endingbalance = LoanAmt
    Priorbalance = Endingbalance
    Interestpaid = Payment * 12
    Principalpaid = 0
    Annualpayment = Payment*12
else:
    Payment = round(numpy.pmt(interestrate / 12, (term - Interestonlyterm) * 12, - LoanAmt, 0, 0), 2)
    if i == 1:
        Priorbalance = LoanAmt
    else:
        Priorbalance = round(numpy.pv(interestrate / 12, (term - i + 1) * 12, Payment, 0, 0) * -1, 2)
    Endingbalance = round(numpy.pv(interestrate/12, (term-i)*12, Payment, 0, 0)*-1, 2)
    Principalpaid = round((Priorbalance-Endingbalance), 2)
    Interestpaid = round((Payment* 12 - Principalpaid), 2)
    Annualpayment = round(Payment*12, 2)

data = [Principalpaid]
df = pandas.DataFrame(data, index=[i], columns=['Principal Paid'])
print(df)


i=i+1

1 个答案:

答案 0 :(得分:0)

您可以构造一个变量(例如paid_list),该变量包含while循环期间的付费信息列表,然后最后只创建一次数据框,我认为您不需要多个数据框您在每次迭代中创建了一个

paid_list = list()
while i<=term:
  if i <= Interestonlyterm:
    Payment = round(LoanAmt * interestrate / 12, 2)
    Endingbalance = LoanAmt
    Priorbalance = Endingbalance
    Interestpaid = Payment * 12
    Principalpaid = 0
    Annualpayment = Payment*12
  else:
    Payment = round(numpy.pmt(interestrate / 12, (term - Interestonlyterm) * 12, - LoanAmt, 0, 0), 2)
    if i == 1:
        Priorbalance = LoanAmt
    else:
        Priorbalance = round(numpy.pv(interestrate / 12, (term - i + 1) * 12, Payment, 0, 0) * -1, 2)
    Endingbalance = round(numpy.pv(interestrate/12, (term-i)*12, Payment, 0, 0)*-1, 2)
    Principalpaid = round((Priorbalance-Endingbalance), 2)
    Interestpaid = round((Payment* 12 - Principalpaid), 2)
    Annualpayment = round(Payment*12, 2)
  paid_list += [Principalpaid]


df = pandas.DataFrame({'Principal Paid': paid_list}) 
print(df)