In property management and accommodation billing, rental fees depend on check-in timestamps, elapsed duration, and departmental discount allowances. In this exercise, process an accommodation roster (rent-calculation.xlsx), audit missing student IDs, calculate elapsed stay days relative to a base billing date, allocate free days using conditional np.where(), and flag overdue stays.
Company-provided accommodations house interns across multiple departments. Each intern has a check-in date (ck_date) and departmental free days policy (Marketing: 50 days; Production: 65 days; Planning: 45 days). Download the practice Excel workbook below:
Download rent-calculation.xlsx ↓
id is missing (isnull()).diff_days) from the check-in date relative to the base billing date of June 1, 2020.allowed column assigning departmental free days (50 for 'mktg', 65 for 'production', 45 for 'planning') using np.where().import pandas as pd
import numpy as np
# 1. Load Excel file
df_rent = pd.read_excel("download/rent-calculation.xlsx")
print("Columns:", df_rent.columns.tolist())
# 2. Department counts
print("\nStudents by Dept:\n", df_rent["dept"].value_counts())
# 3. Missing IDs
missing_ids = df_rent[df_rent["id"].isnull()]
print(f"\nMissing ID Records: {len(missing_ids)}")
assert len(missing_ids) == 2
# 4. Elapsed days relative to June 1, 2020
df_rent["ck_date"] = pd.to_datetime(df_rent["ck_date"])
base_date = pd.to_datetime("2020-06-01")
df_rent["diff_days"] = (base_date - df_rent["ck_date"]).dt.days
# 5. Over 200 days stay
over_200 = df_rent[df_rent["diff_days"] > 200]
print(f"\nStayed > 200 days: {len(over_200)} students")
# 6. Allocate free days policy
df_rent["allowed"] = np.where(
df_rent["dept"] == "mktg", 50,
np.where(df_rent["dept"] == "production", 65,
np.where(df_rent["dept"] == "planning", 45, np.nan))
)
# 7. Identify chargeable overstay students
billable = df_rent[df_rent["diff_days"] > df_rent["allowed"]]
print(f"\nBillable Overstay Students: {len(billable)}")
print(billable[["name", "dept", "diff_days", "allowed"]])
assert len(billable) > 0
Using np.where() provides vector-optimized conditional assignment without slow row-by-row lambda functions:
df_rent["allowed"] = np.where(
df_rent["dept"] == "mktg", 50,
np.where(df_rent["dept"] == "production", 65,
np.where(df_rent["dept"] == "planning", 45, np.nan))
)
Open in Google Colab View on GitHub
Run all check-in duration calculations, nested np.where allocations, and billable stay filters interactively in Google Colab.
Reference: Pandas Time Series documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.