{% extends "base.html" %} {% block title %}Distributed Processing - Data Science Lab{% endblock %} {% block content %}

๐Ÿ“– Why Distributed Processing?

When a single machine can't handle the data or compute, we distribute work across a cluster of machines.

FrameworkBest ForUse Case
DaskScaling pandas workflowsProcessing 10 years of housing data
PySparkPetabyte-scale ETLTransport Authority taxi GPS data (billions of rows)
MapReduceBatch processing conceptCounting word frequency across documents

๐Ÿ“– Dask โ€” Parallel Pandas

Python
import dask.dataframe as dd

# Dask reads data lazily โ€” no memory overflow
ddf = dd.read_csv('housing_data_*.csv')   # Multiple files as partitions

# Same pandas API โ€” but executed in parallel
result = (
    ddf[ddf['town'] == 'DOWNTOWN']
    .groupby('property_type')['price']
    .mean()
    .compute()   # โ† Triggers actual computation
)
print(result)

# Key Dask concepts:
# 1. Lazy evaluation โ€” nothing runs until .compute()
# 2. Partitions โ€” data is split across workers
# 3. Task graph โ€” Dask builds a DAG of operations

๐Ÿ“– PySpark โ€” Big Data at Scale

Python
from pyspark.sql import SparkSession
from pyspark.sql.functions import avg, count, col

spark = SparkSession.builder.appName("SG_housing").getOrCreate()

# Read data into a distributed DataFrame
df = spark.read.csv("housing_data_full.csv", header=True, inferSchema=True)

# Transformations (lazy โ€” builds execution plan)
result = (
    df.filter(col("town") == "DOWNTOWN")
      .groupBy("property_type")
      .agg(
          avg("price").alias("avg_price"),
          count("*").alias("count")
      )
      .orderBy("avg_price", ascending=False)
)

# Action (triggers execution across cluster)
result.show()

# +----------+----------+-----+
# | property_type| avg_price|count|
# +----------+----------+-----+
# |PREMIUM | 820000.0 |  45 |
# | LARGE   | 650000.0 | 120 |
# | MEDIUM   | 480000.0 | 350 |
# | SMALL   | 350000.0 | 200 |
# +----------+----------+-----+

๐Ÿ“– MapReduce Pattern

Python
from functools import reduce
from collections import Counter

# Simulating MapReduce for housing price analysis
data_partitions = [
    [("DOWNTOWN", 500000), ("MIDTOWN", 420000), ("DOWNTOWN", 520000)],
    [("MIDTOWN", 430000), ("DOWNTOWN", 510000), ("GREENFIELD", 350000)],
    [("GREENFIELD", 360000), ("MIDTOWN", 440000), ("GREENFIELD", 340000)],
]

# MAP phase: Each partition emits (key, value) pairs
def map_fn(partition):
    return [(town, price) for town, price in partition]

# SHUFFLE: Group by key (handled by framework)
def shuffle(mapped_results):
    groups = {}
    for pairs in mapped_results:
        for town, price in pairs:
            groups.setdefault(town, []).append(price)
    return groups

# REDUCE phase: Aggregate values for each key
def reduce_fn(key, values):
    return (key, sum(values) / len(values), len(values))

# Execute MapReduce
mapped = [map_fn(p) for p in data_partitions]          # Parallel
shuffled = shuffle(mapped)                              # Framework
results = [reduce_fn(k, v) for k, v in shuffled.items()] # Parallel

for town, avg_price, count in results:
    print(f"{town}: avg ${avg_price:,.0f} ({count} transactions)")
โš ๏ธ Common Mistakes
๐Ÿงช Exercises

1. Write a MapReduce function that finds the maximum price per town.

2. When would you choose Dask over PySpark? List 3 criteria.

3. Explain what "data skew" means using an housing resale example.

{% endblock %}