AnalystPath

Average Nightly Rate Earned per Room

PandasEasyJunior level~10 min

Problem

You are given two DataFrames.

`ratecards` has columns `room_id`, `from_date`, `to_date`, and `rate`. Each row sets the nightly `rate` for a room over an inclusive date period `from_date`..`to_date`. For one room, no two periods overlap.

`bookings` has columns `room_id`, `stay_date`, and `nights`. Each row records `nights` of a room sold starting on `stay_date`. This DataFrame may contain duplicate rows.

For each room in `ratecards`, compute the weighted average nightly rate actually earned, weighting each booking by its `nights`, rounded to 2 decimals. A room with no bookings has an average of 0.

Return `room_id` and `avg_rate`.

Input data

Example rows — the live problem includes the full dataset.

ratecards
room_idfrom_dateto_daterate
12021-02-172021-02-285
12021-03-012021-03-2220
22021-02-012021-02-2015
22021-02-212021-03-3130
bookings
room_idstay_datenights
12021-02-25100
12021-03-0115
22021-02-10200
22021-03-2230

Expected output

Your answer should return 2 rows with the columns room_id, avg_rate.

Starter code (Pandas (Python))

import pandas as pd

def average_nightly_rate(ratecards, bookings) -> pd.DataFrame:
    # Your code here
    return ratecards

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