我怎样才能使这个循环更有效率?

2024-04-24 11:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我历史上收集了50万笔贷款,其中一些已经违约,另一些没有。我的数据帧是lcd_templcd_temp有关于贷款规模(loan_amnt)、贷款是否违约(Total Defaults)、年贷款利率(clean_rate)、贷款期限(clean_term)和从发放到违约的月份(mos_to_default)的信息。^如果没有默认值,{}等于clean_term。你知道吗

我想计算每笔贷款的累计现金流[cum_cf],作为违约前支付的所有优惠券加上(1-严重性)如果贷款违约,只要loan_amnt如果它按时偿还。你知道吗

这是我的代码,它需要很长时间才能运行:

severity = 1

for i in range (0,len(lcd_temp['Total_Defaults'])-1):
    if (lcd_temp.loc[i,'Total_Defaults'] ==1):
    # Default, pay coupon only until time of default, plus (1-severity)
        lcd_temp.loc[i,'cum_cf'] = ((lcd_temp.loc[i,'mos_to_default'] /12)  * lcd_temp.loc[i,'clean_rate'])+(1 severity)*lcd_temp.loc[i,'loan_amnt']
    else: 
    # Total cf is sum of coupons (non compounded) + principal 
        lcd_temp.loc[i,'cum_cf'] = (1+lcd_temp.loc[i,'clean_term']/12* lcd_temp.loc[i,'clean_rate'])*lcd_temp.loc[i,'loan_amnt']

欢迎提出任何关于提高速度的想法或建议(到目前为止需要一个多小时的时间)!你知道吗


Tags: cleandefaultlcdratetemploccftotal
1条回答
网友
1楼 · 发布于 2024-04-24 11:50:46

假设您使用的是Pandas/NumPy,替换if-then结构(例如您正在使用的结构)的标准方法是使用^{}mask是一个布尔值数组。如果为True,则返回来自A的相应值。如果为False,则返回B中相应的值。结果是一个与mask形状相同的数组,其值来自A和/或B。你知道吗

severity = 1

mask = (lcd_temp['Total_Defaults'] == 1)
A = (((lcd_temp['mos_to_default'] /12) * lcd_temp['clean_rate'])
     + (1 severity)*lcd_temp['loan_amnt'])
B = (1+lcd_temp['clean_term']/12 * lcd_temp['clean_rate'])*lcd_temp['loan_amnt']

lcd_temp['cum_cf'] = np.where(mask, A, B)

请注意,这将对整列而不是逐行执行计算。这大大提高了性能,因为它使Pandas/NumPy有机会将更大的值数组传递给快速的底层C/Fortran函数(在本例中,是为了执行算术)。当您一行一行地工作时,您正在Python循环中执行标量算法,这给NumPy提供了零的机会。 如果您必须逐行计算,那么使用纯Python也会很好(也许更好)。你知道吗

即使AB计算整个列的值,并且np.where返回的最终结果中没有使用某些值,但这仍然比假设行的数目不多的情况下逐行计算要快。你知道吗

相关问题 更多 >