【问题标题】:Creating New Column in Pandas Using Value from Previous Cell使用上一个单元格中的值在 Pandas 中创建新列
【发布时间】:2022-08-14 02:57:02
【问题描述】:

我正在尝试使用 Pandas 构建现金流贷款模型表。我已经生成了一些我需要的字段,例如期初余额、利息、本金、付款、期末余额 - 如下所示:

Beginning Balance Principal Payment Interest Ending Bal
50000.00 144.49 477.83 333.33 49855.51
49855.51 145.46 477.83 332.37 49710.05
49710.05 146.43 477.83 331.40 49563.63

现在我正在尝试使用一些新数据和现有列生成新列,例如未偿余额、预付本金、冲销本金和收到的预定本金:

SMM = .0184
Default = .0059
Total_SMM_Loss = .975

cf_table.at[1,\'Net Outstanding Balance\'] = cf_table.at[1,\'Beginning Balance\']

cf_table[\'Scheduled Principle Received\'] = cf_table[\'Principal\'] * Total_SMM_Loss

cf_table[\'Prepaid Principal\'] = cf_table[\'Net Outstanding Balance\'] * SMM

cf_table[\'Charge-Off Principal\'] = cf_table[\'Net Outstanding Balance\'] * Default

cf_table.at[2:,\'Net Outstanding Balance\'] = cf_table[\'Net Outstanding Balance\'] - cf_table[\'Scheduled Principle Received\'] - cf_table[\'Prepaid Principal\'] - cf_table[\'Charge-Off Principal\']

对于净未结余额列,我将第一个单元格的值设置为 50,000 - 贷款的期初余额。接下来我将创建其他列,其中一些依赖于净未结余额的值。

对于在净未偿列中下降的单元格 2,我试图插入一个新公式,该公式将净未偿余额的先前值纳入其计算,同时从预付、冲销和预定原则列中减去值将上一行插入公式。

但是,下表是我在应用上面的代码时收到的信息:

Net Outstanding Balance Prepaid Charge-Off Scheduled Principle
50000.00 920.00 295.00 140.88
NaN NaN NaN 141.82
NaN NaN NaN 142.77
  • 您在寻找.shift().diff() 吗?
  • pandas 擅长矢量化操作等。如上所述,您的过程听起来非常程序化。通常,这些类型的复利问题可以通过计算数学来向量化,并结合cumprod() 和其他简单的算术一次表达所有行。

标签: python pandas


【解决方案1】:

我已经弄清楚了我在上面的帖子中想要完成的事情。在post here 的一些帮助下,我能够将这段代码放在一起来填写这张表的其余部分:

cf_table1.loc[1, 'Net Outstanding Balance'] = 50000

for i in range(2, len(cf_table)):
    cf_table1.loc[i, 'Net Outstanding Balance'] = cf_table1.loc[i-1, 'Net Outstanding Balance'] - cf_table1.loc[i, 'Prepaid Principal'] - cf_table1.loc[i, 'Charge-Off Principal'] - cf_table1.loc[i, 'Scheduled Principle Received']
    cf_table1.loc[i-1, 'Prepaid Principal'] = cf_table1.loc[i-1, 'Net Outstanding Balance'] * SMM
    cf_table1.loc[i-1, 'Charge-Off Principal'] = cf_table1.loc[i-1, 'Net Outstanding Balance'] * Default

cf_table1.head(cf_table1. shape[0] -1)
Net Outstanding Balance Prepaid Charge-Off Scheduled Principle
50000.00 920.00 295.00 140.88
47320.25 895.05 287.00 141.82
46028.40 870.69 279.19 142.77

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2017-10-29
    • 1970-01-01
    相关资源
    最近更新 更多