Read a CSV without losing leading zeros
Pandas data engineering interview problem. Difficulty: beginner. Pattern: String Functions. About 10 minutes. Free to practice.
Load CSV text so zip codes keep their leading zeros and day-first dates become real dates. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
raw is the text of a CSV file with the columns store_id, zip, opened_on and sales. Zip codes are text and some start with 0. opened_on is written day first (DD/MM/YYYY). sales is empty for a store that has not reported. Load raw into a DataFrame and return 1 row per store with: store_id zip: text, leading zeros kept opened_month: the month of opened_on as a number from 1 to 12 sales: a missing value stays missing Keep the rows in file order. Assign the DataFrame to result.
Requirements
- Return the columns store_id, zip, opened_month, sales in that order.
- Keep the file order and use a clean 0..n-1 index.
Constraints
- raw is valid CSV text with a header row.
- opened_on is always DD/MM/YYYY.
- zip is always 5 characters.
Examples
Input: raw store_id,zip,opened_on,sales S1,02134,01/04/2023,1200.5 S2,10001,15/05/2023,980 S3,00501,30/06/2023, S4,94105,03/07/2023,455.25 Output: store_id | zip | opened_month | sales S1 | 02134 | 4 | 1200.5 S2 | 10001 | 5 | 980 S3 | 00501 | 6 | NULL S4 | 94105 | 7 | 455.25 Zip codes keep their zeros (02134, 00501), 01/04/2023 is 1 April so its month is 4, and S3 keeps an empty sales value.
Topics: lakebench, pandas, read_csv, dtype, dates.
More interview problems · All interview problems · Learn data engineering
Read a CSV without losing leading zeros
Interview-style drill: Load CSV text so zip codes keep their leading zeros and day-first dates become real dates.
`raw` is the text of a CSV file with the columns `store_id`, `zip`, `opened_on` and `sales`. Zip codes are text and some start with `0`. `opened_on` is written day first (`DD/MM/YYYY`). `sales` is empty for a store that has not reported. Load `raw` into a DataFrame and return 1 row per store with: - `store_id` - `zip`: text, leading zeros kept - `opened_month`: the month of `opened_on` as a number from 1 to 12 - `sales`: a missing value stays missing Keep the rows in file order. Assign the DataFrame to `result`.