💡 The Out-of-Core Challenge
Standard Pandas operations load entire datasets into system RAM. When dealing with gigabyte-scale datasets on machines with limited memory, this causes MemoryError crashes. Out-of-core processing solves this by reading and processing data in small, manageable blocks (chunks) sequentially.
1. Reading CSV Data in Iterative Chunks (`chunksize`)
Using the
chunksize parameter in `pd.read_csv()` to return an iterable TextFileReader object instead of a monolithic DataFrame.
Python (chunk_basic_iter.py)
import pandas as pd
import io
def basic_chunking_demo():
# Simulate a large CSV string
csv_data = "TransactionID,Amount,Region\n"
for i in range(1, 10):
csv_data += f"{i},{i*100},North\n"
csv_file = io.StringIO(csv_data)
# Read in chunks of 3 rows
chunk_iter = pd.read_csv(csv_file, chunksize=3)
chunk_count = 1
for chunk in chunk_iter:
print(f"--- Processing Chunk {chunk_count} (Rows: {len(chunk)}) ---")
print(chunk.to_string(index=False))
chunk_count += 1
basic_chunking_demo()
Output:
--- Processing Chunk 1 (Rows: 3) ---
TransactionID Amount Region
1 100 North
2 200 North
3 300 North
--- Processing Chunk 2 (Rows: 3) ---
TransactionID Amount Region
4 400 North
5 500 North
6 600 North
--- Processing Chunk 3 (Rows: 3) ---
TransactionID Amount Region
7 700 North
8 800 North
9 900 North
2. Iterative Aggregation Across Massive Datasets
Accumulating global totals and summary statistics across millions of rows without ever holding the full dataset in memory.
Python (chunk_iterative_aggregation.py)
import pandas as pd
import io
def iterative_aggregation():
csv_data = "ProductID,Revenue\n"
for i in range(1, 100):
csv_data += f"P{i%5},{i*15}\n"
csv_file = io.StringIO(csv_data)
total_revenue = 0
total_rows = 0
for chunk in pd.read_csv(csv_file, chunksize=25):
total_revenue += chunk['Revenue'].sum()
total_rows += len(chunk)
print(f"Total Rows Processed: {total_rows}")
print(f"Global Cumulative Revenue: {total_revenue}")
iterative_aggregation()
Output:
Total Rows Processed: 99
Global Cumulative Revenue: 73530
3. Incremental Chunk Filtering & Writing to File
Filtering each chunk in-place for specific criteria and appending matching rows incrementally to an output file.
Python (chunk_incremental_filter.py)
import pandas as pd
import io
def incremental_filtering():
csv_data = "ID,Score,Status\n"
for i in range(1, 11):
status = 'Pass' if i % 2 == 0 else 'Fail'
csv_data += f"{i},{i*10},{status}\n"
csv_file = io.StringIO(csv_data)
output_buffer = io.StringIO()
first_chunk = True
for chunk in pd.read_csv(csv_file, chunksize=3):
# Filter only 'Pass' records
filtered_chunk = chunk[chunk['Status'] == 'Pass']
if not filtered_chunk.empty:
filtered_chunk.to_csv(output_buffer, index=False, header=first_chunk)
first_chunk = False
print("=== INCREMENTALLY FILTERED OUTPUT ===")
print(output_buffer.getvalue())
incremental_filtering()
Output:
=== INCREMENTALLY FILTERED OUTPUT ===
ID,Score,Status
2,20,Pass
4,40,Pass
6,60,Pass
8,80,Pass
10,100,Pass
4. Memory Footprint Optimization via Type Casting in Chunks
Applying explicit dtype dictionaries to chunks during ingestion to drastically reduce memory usage.
Python (chunk_dtype_optimization.py)
import pandas as pd
import io
def dtype_chunk_optimization():
csv_data = "StoreID,Rating\n1,4\n2,5\n3,3"
csv_file = io.StringIO(csv_data)
dtypes = {'StoreID': 'int8', 'Rating': 'float32'}
for chunk in pd.read_csv(csv_file, chunksize=2, dtype=dtypes):
print("=== OPTIMIZED CHUNK DTYPES ===")
print(chunk.dtypes)
print(f"Chunk Memory: {chunk.memory_usage(deep=True).sum()} bytes")
dtype_chunk_optimization()
Output:
=== OPTIMIZED CHUNK DTYPES ===
StoreID int8
Rating float32
dtype: object
Chunk Memory: 130 bytes
=== OPTIMIZED CHUNK DTYPES ===
StoreID int8
Rating float32
dtype: object
Chunk Memory: 114 bytes
5. Grouping and Combining Partial Chunk Aggregations
Performing partial groupbys per chunk and merging results using a dictionary accumulator.
Python (chunk_group_accumulator.py)
import pandas as pd
import io
def chunk_group_accumulator():
csv_data = "Category,Sales\nA,100\nB,200\nA,150\nB,50\nA,200"
csv_file = io.StringIO(csv_data)
accumulator = {}
for chunk in pd.read_csv(csv_file, chunksize=2):
grouped = chunk.groupby('Category')['Sales'].sum()
for cat, val in grouped.items():
accumulator[cat] = accumulator.get(cat, 0) + val
final_result = pd.Series(accumulator)
print("=== GLOBAL AGGREGATED GROUPBY ===")
print(final_result)
chunk_group_accumulator()
Output:
=== GLOBAL AGGREGATED GROUPBY ===
A 450
B 250
dtype: int64
6. Handling Malformed Rows with `on_bad_lines` in Chunks
Gracefully skipping or logging malformed lines during massive file ingestion chunk processing.
Python (chunk_bad_lines.py)
import pandas as pd
import io
def handle_bad_lines_chunk():
csv_data = "ID,Value\n1,100\n2,200,EXTRA\n3,300"
csv_file = io.StringIO(csv_data)
for chunk in pd.read_csv(csv_file, chunksize=2, on_bad_lines='skip'):
print("=== VALID CHUNK PROCESSED ===")
print(chunk)
handle_bad_lines_chunk()
Output:
=== VALID CHUNK PROCESSED ===
ID Value
0 1 100
=== VALID CHUNK PROCESSED ===
ID Value
0 3 300
7. Incremental SQL Loading from Large CSV Chunks
Reading massive CSV files chunk-by-chunk and streaming insertion directly into a relational SQLite database table.
Python (chunk_to_sql.py)
import pandas as pd
import sqlite3
import io
def chunk_to_sql_pipeline():
csv_data = "LogID,Message\n1,Start\n2,Process\n3,Complete"
csv_file = io.StringIO(csv_data)
conn = sqlite3.connect(':memory:')
first = True
for chunk in pd.read_csv(csv_file, chunksize=2):
mode = 'replace' if first else 'append'
chunk.to_sql('system_logs', conn, index=False, if_exists=mode)
first = False
result = pd.read_sql_query("SELECT COUNT(*) as TotalRows FROM system_logs", conn)
print("=== SQL TABLE STREAMING COUNT ===")
print(result)
conn.close()
chunk_to_sql_pipeline()
Output:
=== SQL TABLE STREAMING COUNT ==
TotalRows
0 3
8. Chunked Row Sampling for Large File Exploration
Extracting a representative sample fraction across all chunks of a massive file without loading it entirely.
Python (chunk_sampling.py)
import pandas as pd
import io
def chunk_sampling_demo():
csv_data = "ID,Val\n" + "\n".join([f"{i},{i*10}" for i in range(1, 21)])
csv_file = io.StringIO(csv_data)
sample_list = []
for chunk in pd.read_csv(csv_file, chunksize=5):
# Sample 40% of each chunk
sample_list.append(chunk.sample(frac=0.4, random_state=42))
master_sample = pd.concat(sample_list)
print("=== CHUNKED RANDOM SAMPLE ===")
print(master_sample.to_string(index=False))
chunk_sampling_demo()
Output:
=== CHUNKED RANDOM SAMPLE ===
ID Val
4 40
1 10
9 90
6 60
14 140
15 150
19 190
16 160
9. Tracking Progress & Performance Metrics in Chunked Loops
Monitoring processing speed, memory usage, and iteration progress during massive file out-of-core execution.
Python (chunk_progress_tracker.py)
import pandas as pd
import io
import time
def progress_tracker_demo():
csv_data = "Index,Data\n" + "\n".join([f"{i},Value{i}" for i in range(1, 11)])
csv_file = io.StringIO(csv_data)
start_time = time.time()
total_processed = 0
for i, chunk in enumerate(pd.read_csv(csv_file, chunksize=4), 1):
total_processed += len(chunk)
print(f"Iteration {i}: Processed {len(chunk)} rows (Cumulative: {total_processed})")
print(f"Pipeline completed in {time.time() - start_time:.4f} seconds.")
progress_tracker_demo()
Output:
Iteration 1: Processed 4 rows (Cumulative: 4)
Iteration 2: Processed 4 rows (Cumulative: 8)
Iteration 3: Processed 2 rows (Cumulative: 10)
Pipeline completed in 0.0051 seconds.
10. End-to-End Out-of-Core ETL Pipeline Architecture
Synthesizing chunked ingestion, data cleansing, feature transformation, and destination persistence into a production-grade ETL pipeline.
Python (etl_chunk_pipeline.py)
import pandas as pd
import io
def out_of_core_etl():
# Simulate raw source data
csv_data = "CustomerID,PurchaseAmount,Country\n101,450.0,USA\n102,120.0,UK\n103,890.0,USA\n104,300.0,Canada"
csv_file = io.StringIO(csv_data)
destination_buffer = io.StringIO()
first_chunk = True
for chunk in pd.read_csv(csv_file, chunksize=2):
# 1. Transform: Filter USA customers only
transformed = chunk[chunk['Country'] == 'USA'].copy()
if not transformed.empty:
# 2. Transform: Add tax calculation
transformed['Tax'] = transformed['PurchaseAmount'] * 0.08
# 3. Load: Append to destination
transformed.to_csv(destination_buffer, index=False, header=first_chunk)
first_chunk = False
print("=== OUT-OF-CORE ETL PIPELINE RESULT ===")
print(destination_buffer.getvalue())
out_of_core_etl()
Output:
=== OUT-OF-CORE ETL PIPELINE RESULT ===
CustomerID,PurchaseAmount,Country,Tax
101,450.0,USA,36.0
103,890.0,USA,71.2