cswork / libraryOpen practice workspace

Coding questions · Affirm

Analyze Loan Payments Using Pandas for Key Insights

This question evaluates data manipulation and aggregation skills using pandas, focusing on computing per-loan payment totals, payment success rates, and a repayment-status flag. It is commonly asked to assess applied data wrangling and numeric summarization abilities in the Data Manipulation (SQL/Python) domain, testing practical application rather than purely conceptual understanding.

loan_payments

+------------+------------+-------------+-----------+---------+
| loan_id    | payment_id | payment_date | amount    | status  |
+------------+------------+-------------+-----------+---------+
| L1         | P1         | 2023-01-15   | 250.00    | success |
| L1         | P2         | 2023-02-15   | 250.00    | success |
| L1         | P3         | 2023-03-15   | 250.00    | success |
| L1         | P4         | 2023-04-15   | 250.00    | success |
| L2         | P5         | 2023-01-20   | 500.00    | failed  |
+------------+------------+-------------+-----------+---------+
Scenario

Credit Risk – Analyze loan-payment data with pandas

Question

Using pandas, load the loan_payments table below and compute: (a) total amount paid per loan_id, (b) payment success rate per loan_id, and (c) a flag indicating whether the loan has been fully repaid ($1,000 principal). Return the resulting DataFrame.

Hints

Use groupby, agg, and boolean logic.

Loan payment success rate and repayment status per loan

Write an SQL query on the loan_payments table to compute, for each loan_id: (a) total amount paid from successful payments only, (b) payment success rate defined as successful payments divided by total payments, and (c) a flag fully_repaid that is 1 if total_paid is at least 1000 (the loan principal) and 0 otherwise. Return one row per loan_id.

Table loan_payments

columntypeconstraints
loan_idVARCHAR
payment_idVARCHAR
payment_dateDATE
amountDECIMAL(10,2)
statusVARCHAR

Sample data:

amountloan_idpayment_datepayment_idstatus
250L12023-01-15P1success
250L12023-02-15P2success
250L12023-03-15P3success
250L12023-04-15P4success
500L22023-01-20P5failed

Expected output

One row per loan_id with: total_paid = sum of amounts from successful payments only; success_rate = count of successful payments divided by total payments; fully_repaid = 1 if total_paid >= 1000, else 0.

fully_repaidloan_idsuccess_ratetotal_paid
1L111000
0L200

Hints

  1. Use GROUP BY loan_id with conditional aggregation (CASE WHEN).
  2. Compute total_paid by summing amount only when status = 'success'.
  3. Compute success_rate as AVG(CASE WHEN status = 'success' THEN 1.0 ELSE 0.0 END).
  4. Flag fully repaid with CASE WHEN SUM(CASE WHEN status = 'success' THEN amount ELSE 0 END) >= 1000 THEN 1 ELSE 0 END.