Clean and Merge Housing Data
Capital OneData Scientist · OnsiteLast updated
This question tests the ability to clean messy housing datasets, handle inconsistent data types, and perform efficient left-joins with external reference data.
Problem Statement
You are working with two datasets: a primary housing_data DataFrame containing listing information and a zipcode_reference DataFrame containing regional demographic data.
Datasets
-
housing_data(columns:listing_id,price,zip_code):price: Contains numeric values stored as strings (e.g., "$1,200"), or sometimes null.zip_code: Often missing leading zeros (e.g., 902 vs "00902") and contains inconsistent types.
-
zipcode_reference(columns:zip,median_income):zip: Guaranteed to be a 5-digit string (e.g., "00902").
Task
Write a function clean_and_merge(housing_df, zip_df) that returns a cleaned DataFrame.
- Price Cleaning: Convert the
pricecolumn to a numeric float. If a price is null, impute it with the global mean of the non-null price values. - Zip Code Standardization: Standardize
zip_codein the primary dataset to a 5-digit string, padding with leading zeros where necessary. - Merge: Perform a left join to include
median_incomefromzip_dfontohousing_df.
Example
Input housing_df:
listing_id price zip_code
0 1 $500 123
1 2 $700 0123
2 3 NaN 9999
Input zip_df:
zip median_income
0 00123 50000
1 09999 60000
Expected Output:
listing_id price zip_code median_income
0 1 500 00123 50000.0
1 2 700 00123 50000.0
2 3 600 09999 60000.0
Hints
Hint 1
Use pandas string accessors (str.replace) to remove currency symbols and commas before converting to float.
Hint 2
The .zfill(5) method on string-converted columns is the most efficient way to handle zip code padding.
Hint 3
Always check for duplicates in the reference table before merging to ensure the shape of your primary DataFrame does not unexpectedly grow.
Follow-up questions
- How would you handle zip codes that exist in the housing data but are missing from the reference table?
- If the dataset scaled to 100 million rows, what optimizations would you consider instead of using pandas?
- How would you validate that your imputation strategy did not introduce significant bias into the price distribution?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.