Working with Files and DataFrames in Python
Read and write CSV, JSON and Parquet in Python, and use pandas, Polars or DuckDB for small to medium transformations before reaching for Spark.
Beginner · about 10 hours · difficulty 2/5
Learn first: Python Fundamentals
A lot of data engineering is moving files around and reshaping them. For data that fits on one machine (up to a few GB), Python libraries are faster to build with than a distributed system.
Standard library
csvmodule for streaming CSV row by row, handling quoting and delimiters correctly.jsonfor JSON documents and JSON Lines (one JSON object per line), the common format for logs and API dumps.pathlibfor paths,gzipfor compressed files.
pandas essentials
- Reading:
read_csvwithdtype,parse_datesandusecolsto control memory. - Core operations: filtering,
groupby,merge,pivot_table, handling nulls withisnaandfillna. - Writing:
to_parquet(via pyarrow) instead of CSV whenever the consumer allows it. - Chunking:
read_csv(..., chunksize=100_000)for files larger than memory.
Modern alternatives
- Polars: a fast DataFrame library with a lazy query engine; great for larger single-machine jobs.
- DuckDB: an in-process SQL engine that can query CSV and Parquet files directly.
SELECT city, SUM(amount) FROM 'orders/*.parquet' GROUP BY 1runs on your laptop in seconds.
Knowing when one machine is enough saves companies real money.
Pitfalls
- Letting pandas guess types: phone numbers and PIN codes become floats and lose leading zeros.
- Using
iterrowsin loops over millions of rows. Use vectorised operations or SQL. - Silently dropping rows in a merge. Check row counts before and after every join.
You are ready to move on when you can take a messy 1 GB CSV, clean the types, deduplicate, aggregate it and write partitioned Parquet, and explain why you chose pandas, Polars or DuckDB.
Key concepts
- csv and json modules
- JSON Lines
- pandas read, transform, write
- Explicit dtypes and memory
- Chunked processing
- Polars: Lazy, multi-threaded DataFrames
- DuckDB: SQL over local files
- pyarrow and Parquet
Mini project
Take a public dataset (for example Indian Railways or air quality data from data.gov.in), clean it with pandas, then repeat the same aggregation in DuckDB SQL. Compare runtime and memory, and write the result to Parquet.
Check yourself
A merge between orders (1M rows) and customers returns 1.4M rows. What happened and how do you find the cause?
Free resources
- pandas documentation (pandas)
- DuckDB documentation (DuckDB)
- Python csv module (Python.org)
- Apache Arrow Python docs (Apache Arrow)