gpt4 book ai didi

python - Pandas 中的条件累积和

转载 作者:太空狗 更新时间:2023-10-29 20:30:58 26 4
gpt4 key购买 nike

我是一名前 Excel 高级用户,正在为自己的罪行忏悔。我需要帮助为我重新创建一个通用计算。

我正在尝试计算贷款组合的绩效。在分子中,我正在计算累计损失总额。在分母中,我需要包含在累计总额中的贷款的原始余额。

我不知道如何在 Pandas 中进行条件分组来完成此操作。它在 Excel 中非常简单,所以我希望我想多了。

我在 StackOverflow 上找不到太多关于这个问题的信息,但这是最接近的:python pandas conditional cumulative sum

我想不通的是我的条件是基于索引中的值并包含在列中

下面是我的数据:

| Loan    | Origination | Balance | NCO Date  | NCO | As of Date | Age     (Months) | NCO Age (Months) |
|---------|-------------|---------|-----------|-----|------------|--------------|------------------|
| Loan 1 | 1/31/2011 | 1000 | 1/31/2018 | 25 | 5/31/2019 | 100 | 84 |
| Loan 2 | 3/31/2011 | 2500 | | 0 | 5/31/2019 | 98 | |
| Loan 3 | 5/31/2011 | 3000 | 1/31/2019 | 15 | 5/31/2019 | 96 | 92 |
| Loan 4 | 7/31/2011 | 2500 | | 0 | 5/31/2019 | 94 | |
| Loan 5 | 9/30/2011 | 1500 | 3/31/2019 | 35 | 5/31/2019 | 92 | 90 |
| Loan 6 | 11/30/2011 | 2500 | | 0 | 5/31/2019 | 90 | |
| Loan 7 | 1/31/2012 | 1000 | 5/31/2019 | 5 | 5/31/2019 | 88 | 88 |
| Loan 8 | 3/31/2012 | 2500 | | 0 | 5/31/2019 | 86 | |
| Loan 9 | 5/31/2012 | 1000 | | 0 | 5/31/2019 | 84 | |
| Loan 10 | 7/31/2012 | 1250 | | 0 | 5/31/2019 | 82 | |

在 Excel 中,我会使用以下公式计算此总数:

未结余额线:=SUMIFS(Balance,Age (Months),Reference Age)

Cumulative NCO: =SUMIFS(NCO,Age (Months),>=Reference Age,NCO Age (Months),<=&Reference Age)

数据:

| Reference Age       | 85    | 90    | 95   | 100  
|---------------------|-------|-------|------|------
| Outstanding Balance | 16500 | 13000 | 6500 | 1000
| Cumulative NCO | 25 | 60 | 40 | 25

这里的目标是在未结余额中包含足够旧的东西,以便对 NCO 进行观察。 NCO 是那些未偿还贷款在该点之前发生的总额。

编辑:

我已经通过这种方式进行了计算。但这是最有效的吗?

age_bins = list(np.arange(85, 101, 5))
final_df = pd.DataFrame()
df.fillna(value=0, inplace=True)
df["NCO Age (Months)"] = df["NCO Age (Months)"].astype(int)

for x in age_bins:

age = x

nco = df.loc[(df["Age (Months)"] >= x) & (df["NCO Age (Months)"] <= x), "NCO"].sum()

bal = df.loc[(df["Age (Months)"] >= x), "Balance"].sum()

temp_df = pd.DataFrame(
data=[[age, nco, bal]],
columns=["Age", "Cumulative NCO", "Outstanding Balance"],
index=[age],
)

final_df = final_df.append(temp_df, sort=True)

最佳答案

您根据变量使用复杂的条件。很容易找到简单累积和的矢量化方法,但我无法想象累积 NCO 的好方法。

所以我会回到 Python 理解:

data = [
{ 'Reference Age': ref,
'Outstanding Balance': df.loc[df.iloc[:,6]>=ref,'Balance'].sum(),
'Cumulative NCO': df.loc[(df.iloc[:,6]>=ref)&(df.iloc[:,7]<=ref),
'NCO'].sum() }
for ref in [85, 90, 95, 100]]

result = pd.DataFrame(data).set_index('Reference Age').T

它产生:

Reference Age          85     90    95    100
Cumulative NCO 25 60 40 25
Outstanding Balance 16500 13000 6500 1000

关于python - Pandas 中的条件累积和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56601817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com