Spaces:
Running
Running
Update metrics/mix_metrics.py
Browse files- metrics/mix_metrics.py +89 -0
metrics/mix_metrics.py
CHANGED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# metrics/mix_metrics.py
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def calculate_count_mix(
|
| 7 |
+
df,
|
| 8 |
+
group_col,
|
| 9 |
+
id_col="account_id"
|
| 10 |
+
):
|
| 11 |
+
"""
|
| 12 |
+
Returns count mix across a characteristic.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
result = (
|
| 16 |
+
df.groupby(group_col)[id_col]
|
| 17 |
+
.nunique()
|
| 18 |
+
.reset_index(name="accounts")
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
total_accounts = result["accounts"].sum()
|
| 22 |
+
|
| 23 |
+
result["mix_pct"] = (
|
| 24 |
+
result["accounts"] / total_accounts
|
| 25 |
+
) * 100
|
| 26 |
+
|
| 27 |
+
result = result.sort_values(
|
| 28 |
+
by="accounts",
|
| 29 |
+
ascending=False
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
return result
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def calculate_limit_mix(
|
| 36 |
+
df,
|
| 37 |
+
group_col,
|
| 38 |
+
limit_col="credit_limit"
|
| 39 |
+
):
|
| 40 |
+
"""
|
| 41 |
+
Returns credit limit mix across a characteristic.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
result = (
|
| 45 |
+
df.groupby(group_col)[limit_col]
|
| 46 |
+
.sum()
|
| 47 |
+
.reset_index(name="total_limit")
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
total_limit = result["total_limit"].sum()
|
| 51 |
+
|
| 52 |
+
result["mix_pct"] = (
|
| 53 |
+
result["total_limit"] / total_limit
|
| 54 |
+
) * 100
|
| 55 |
+
|
| 56 |
+
result = result.sort_values(
|
| 57 |
+
by="total_limit",
|
| 58 |
+
ascending=False
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
return result
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def calculate_vintage_mix(
|
| 65 |
+
df,
|
| 66 |
+
vintage_col,
|
| 67 |
+
group_col,
|
| 68 |
+
id_col="account_id"
|
| 69 |
+
):
|
| 70 |
+
"""
|
| 71 |
+
Creates vintage-wise mix table.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
result = (
|
| 75 |
+
df.groupby([vintage_col, group_col])[id_col]
|
| 76 |
+
.nunique()
|
| 77 |
+
.reset_index(name="accounts")
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
total_by_vintage = (
|
| 81 |
+
result.groupby(vintage_col)["accounts"]
|
| 82 |
+
.transform("sum")
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
result["mix_pct"] = (
|
| 86 |
+
result["accounts"] / total_by_vintage
|
| 87 |
+
) * 100
|
| 88 |
+
|
| 89 |
+
return result
|