【发布时间】:2020-03-19 20:14:29
【问题描述】:
我有以下数据集:
危险率的计算公式为:
For Year = 1: Hazard_rate(Year) = PD(Year)
For Year > 1: Hazard_rate(Year) = (PD(Year) + Hazard_rate(Year - 1) * (Year - 1)) / (Year)
假设: 按customer_ID,年份单调且严格> 0
由于这个公式是递归的,并且需要前一年的危险率,我的下面的代码很慢,并且在大型数据集下变得难以管理,有没有办法可以向量化这个操作或至少使循环更快?
#Calculate the hazard rates
#Initialise an array to collect the hazard rate for each calculation, particularly useful for the recursive nature
#of the formula
hr = []
#Loop through the dataframe, executing the hazard rate formula
#If time_period (year) = 1 then the hazard rate is equal to the pd
for index, row in df.iterrows():
if row["Year"] == 1:
hr.append(row["PD"])
elif row["Year"] > 1:
#Create a row_num variable to indicate what the index is for each unique customer ID
row_num = int(row["Year"])
hr.append((row["PD"] + hr[row_num - 2] * (row["Year"] - 1)) / (row["Year"]))
else:
raise ValueError("Index contains negative or zero values")
#Attach the hazard_rates array to the dataframe
df["hazard_rate"] = hr
【问题讨论】:
-
只是为了澄清一下:你一开始说的数据集就是你想要计算的,而你的数据框只有
year和PD列开始? -
使用
df.loc[index, 'hazard_rate'] = *formula results*而不是使用列表会有所帮助吗? -
FBruzzesi,正确 - 我添加了危险率列以供人们验证他们的结果
-
Aryerez,我过去曾尝试使用 .loc。但是,由于公式需要以前的结果,我无法让它工作。能给我看看吗?
-
数据将按年份排序,年份之间严格没有间隔,并且严格没有 0 或负年份,因为这些是预测年份
标签: python pandas loops for-loop vectorization