AnalystPath

Each Reader's Three Latest Loans

PandasMediumMid level~10 min

Problem

A library logs every book loan.

`readers` columns: `reader_id`, `reader_name`.
`loans` columns: `loan_id`, `loaned_on`, `reader_id`, `fine`.

For each reader, report their **three most recent loans** (by loan date, latest first). If a reader has fewer than three loans, return all of them.

Return `reader_name`, `reader_id`, `loan_id`, and `loaned_on`. Order the result by `reader_name`, then `reader_id`, then `loaned_on` descending.

Input data

Example rows — the live problem includes the full dataset.

readers
reader_idreader_name
1Wendell
2Bianca
3Soraya
4Mateo
5Kelyn
loans
loan_idloaned_onreader_idfine
12021-07-31130
22021-07-30240
32021-07-31370
42021-07-294100
52021-06-1011010

Expected output

Your answer should return 9 rows with the columns reader_name, reader_id, loan_id, loaned_on.

Starter code (Pandas (Python))

import pandas as pd

def each_readers_three_latest_loans(readers, loans) -> pd.DataFrame:
    # Your code here
    return readers

Solve this Pandas question free

Write Pandas (Python) and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related Pandas questions