Multiply the rate by the amount, sum both by group, divide. One line that mean() does not replace.
The average rate of a loan book is weighted by the amount lent: a $3 million loan counts ten times more than a $300,000 one. In pandas, add a column rate x principal, sum it and the principal by group, and divide. df["rate"].mean() gives every loan the same weight. On the fictional book of this example, the weighted rate is 7.94% against a simple average of 7.85%.
def by_sector():
df = merged()
df = df.assign(rate_x_principal=df["rate"] * df["principal"])
g = df.groupby("sector").agg(loans=("loan_id", "count"),
principal=("principal", "sum"),
rxp=("rate_x_principal", "sum"))
g["rate"] = g["rxp"] / g["principal"] # weighted by principal
return g.drop(columns="rxp").sort_values("principal", ascending=False)
The product is summed within each group before the division. Dividing first, or averaging the rates of the groups, gives a different and wrong number.
| Sector | Loans | Principal | Weighted rate | Simple average |
|---|---|---|---|---|
| Logistics | 12 | $23,635,000 | 7.95% | 7.77% |
| Manufacturing | 11 | $22,015,000 | 8.11% | 8.12% |
| Technology | 14 | $20,545,000 | 8.01% | 7.88% |
| Healthcare | 9 | $12,880,000 | 7.88% | 7.91% |
| Hospitality | 7 | $8,430,000 | 7.37% | 7.38% |
| Retail | 7 | $6,660,000 | 7.99% | 7.89% |
The largest gap is in Logistics: 7.95% weighted against 7.77% simple. The average of the six sector rates, 7.88%, is a third answer and matches neither: a total is computed from the rows, never from the subtotals.
Original principal describes what was lent; the outstanding balance describes what earns interest today. For the coupon of a book at a reporting date, weight by the balance of the performing loans: on the same book that gives 7.93%. State the weight in the label.
Calder Lane Credit and its loans are fictional; the data were generated by code. Educational material, not investment advice. Prepared with AI assistance.
31 lessons from zero: import, clean and join the files of a finance team, build payment schedules, age arrears, compare vintages, measure yields, draw charts, write the Excel report and reconcile it, on a 60-loan portfolio. Start and solution files, notebooks, exercises and a certificate exam ($199).
Multiply the values by the weights in a new column, sum it and the weights (by group with groupby if needed), and divide the first sum by the second.
mean() gives every loan the same weight. A portfolio rate must weight each loan by its amount, or large and small loans count the same.
The balance outstanding for what the book earns today; the original principal for what was originated. Say which one you used.