Start with profiling and reproducible failure:- Reproduce on a sample worker with the same data subset. Use memory/profiler tools: memory_profiler (mprof), tracemalloc, pandas_profiling for column stats, and line_profiler to find hotlines.- Example: mprof run -o run.dat python transform.py; mprof plot.Optimize algorithm & vectorize:- Replace row-wise apply/lambdas with vectorized ops or NumPy. Example:python
# slow
df['len'] = df['text'].apply(len)
# fast
df['len'] = df['text'].str.len()
- Use boolean masking and .loc instead of iterating.Reduce intermediate copies:- Chain operations carefully and reassign to same column to avoid temporaries. Use inplace where safe (note pandas deprecation caveats).- Example: avoid df = df.merge(...).assign(...).pipe(...) on huge tables; do merges selectively and drop unneeded columns immediately: del df['tmp'] ; gc.collect().Memory layout & dtypes:- Downcast numerics: df['x']=pd.to_numeric(df['x'], downcast='unsigned')- Convert strings with low cardinality to category:python
df['cat']=df['cat'].astype('category')
- Use nullable dtypes only when needed. For timestamps, use datetime64[ns] and consider int64 epoch if faster.- Use memory usage check: df.memory_usage(deep=True).sort_values(ascending=False)Sparse and chunking strategies:- Use pd.read_csv(..., dtype=..., usecols=..., chunksize=1_000_000) to stream and transform per chunk, aggregating results.When to migrate to Dask/Spark:- Stay in pandas if dataset fits comfortably in ~2-3x RAM (after optimizations). Migrate when: - Single-node memory can't handle peak working set even after downcasting/chunking. - You need parallel processing across cores for I/O/CPU bound transforms. - You require distributed storage/compute or integration with cluster resources.- Dask: minimal API changes, good for scaling pandas code on a single cluster; example: import dask.dataframe as dd; ddf = dd.read_parquet(...); use ddf.map_partitions for custom ops.- Spark: choose when you need robust fault tolerance, heavy shuffles, or integrate with Hadoop/S3 at scale. Reimplement heavy UDFs in native Spark SQL or use pandas UDFs (PySpark) carefully.Final checklist:- Profile -> vectorize hot paths -> reduce copies -> tune dtypes & categories -> stream/chunk -> pick Dask for pandas-like scaling, Spark for large distributed ETL and production pipelines.