Big Data Analysis: Spark & Dask


INS-605: Data Analysis II

Lecturer: Dr. Sothea HAS

1 Motivation: Why Big Data?

1.1 A Practical Motivation

  • Imagine that we are analyzing an online retail platform where every transaction contains:
Transaction ID Customer ID Product ID Quantity Unit price Transaction date
0001 101 Laptop 1 900 2024-01-01
\(\dots\) \(\dots\) \(\dots\) \(\dots\) \(\dots\) \(\dots\)
  • Simple business questions we might want to answer:
    • What is the total revenue to date?
    • Which products generate the highest revenue?
    • Who are the most valuable customers?
    • How does revenue evolve over time?
  • These questions can become very challenging to answer when the dataset grows to hundreds of millions of transactions.

Starting with Pandas

  • We can easily analyze a small dataset using Pandas.
transaction_id customer_id product quantity unit_price revenue
0 1 101 Laptop 1 900 900
1 2 102 Phone 2 500 1000
2 3 101 Mouse 3 20 60
3 4 103 Laptop 1 900 900
  • Total revenue for each product can be computed:
Code
pdf.groupby("product")["revenue"].sum().to_frame().T
product Laptop Mouse Phone
revenue 1800 60 1000
  • Things get more complicated with hundreds of millions of transactions. The dataset may not fit in memory, and computations may become slow.

When Does Pandas Fails?

Main idea: We do not need Big Data technology for every dataset. We need it when the scale of data and computation exceeds what our classical tools can handle efficiently.

The 3Vs (or 5Vs) of Big Data

  • Other dimensions are sometimes added, such as veracity (data quality) and value (usefulness).

2 From Classical to Distributed Computing

2.1 Distributed Computing

  • Distributed computing divides a large dataset into smaller partitions and processes them in parallel across multiple workers (machines or CPU cores).
  • This allows for scalability and fault tolerance. If one worker fails, others can continue processing.

Data Partitioning

Classical Pandas

  • The data is processed within one Python process.
# One DataFrame
df = pd.read_csv("sales.csv")

# Process the entire data
total = df["revenue"].sum()

Distributed processing

2.2 Pandas vs PySpark vs Dask

Feature Pandas PySpark Dask
Main purpose Data analysis Distributed processing (JVM) Parallel computing (Python)
Execution Local Distributed or local Local or distributed
API Pandas Similar to SQL/PD Similar to Pandas
Lazy execution No Yes Yes
Large datasets Limited by local resources Designed for large-scale data Designed for parallel computing
Ecosystem Python Apache Spark Python
  • PySpark: A distributed data-processing engine that provides its own optimized execution environment, with Python as an interface.
  • Dask: A parallel and distributed computing framework that coordinates computations performed largely by existing Python libraries.

3 Getting Started with PySpark

3.1 Installing PySpark

  • Apache Spark is a distributed computing framework.
  • PySpark is the Python interface to Apache Spark.
  • Its operation is close to Pandas and SQL.
# Install the pyspark package
pip install pyspark
  • PySpark also requires a compatible Java runtime. Make sure Java is installed and available in your environment.
# Check Java
java -version

Important: For this introduction, we will run Spark locally on our computer. The same programming concepts can later be used on a Spark cluster.

Getting Start with a Spark Session

  • In PySpark, we first create a Spark session.
import os
import sys
os.environ["PYSPARK_PYTHON"] = sys.executable
os.environ["PYSPARK_DRIVER_PYTHON"] = sys.executable

from pyspark.sql import SparkSession
spark = (
    SparkSession.builder
    .appName("BigDataIntroduction")
    .master("local[*]")
    .getOrCreate()
)
  • SparkSession.builder: entry point to configure a Spark session.
  • appName(): name of your application/session.
  • master("local[*]"): run locally using all available CPU cores.
  • getOrCreate(): create or reuse a Spark session.

Intuition: Pandas works directly with local DataFrames. PySpark uses a Spark session to coordinate data processing using JVM-based executors.

Creating a PySpark DataFrame

We can create a Spark DataFrame from the same data used in Pandas.

Code
sales = [
    (1, 101, "Laptop", 1, 900),
    (2, 102, "Phone", 2, 500),
    (3, 101, "Mouse", 3, 20),
    (4, 103, "Laptop", 1, 900),
    (5, 102, "Phone", 1, 500)
]
columns = [
    "transaction_id",
    "customer_id",
    "product",
    "quantity",
    "unit_price"
]
sdf = spark.createDataFrame(sales, columns)
sdf.show() # we show the data
+--------------+-----------+-------+--------+----------+
|transaction_id|customer_id|product|quantity|unit_price|
+--------------+-----------+-------+--------+----------+
|             1|        101| Laptop|       1|       900|
|             2|        102|  Phone|       2|       500|
|             3|        101|  Mouse|       3|        20|
|             4|        103| Laptop|       1|       900|
|             5|        102|  Phone|       1|       500|
+--------------+-----------+-------+--------+----------+

Notice that we use show() rather than simply writing the DataFrame name as we often do in Pandas.

Loading a CSV File

  • The most common way to start an analysis is to load data from a file.

Pandas

pdf = pd.read_csv(
    "sales.csv"
)

pdf.head()

PySpark

sdf = (
    spark.read
    .option("header", True)
    .option("inferSchema", True)
    .csv("sales.csv")
)

sdf.show(5)
  • The main difference is the interface. Spark reads and represents the data as a Spark DataFrame, which can be processed using its execution engine.
  • Pyspark execution engine includes its own SQL and query optimizers, DAG scheduler, task scheduler, shuffle manager, etc.

Inspecting the Data

Pandas

pdf.head()
pdf.shape
pdf.info()
pdf.describe()
pdf.columns

PySpark

sdf.show(5)
sdf.count()
sdf.printSchema()
sdf.describe().show()
sdf.columns
  • Remark: count() is an action in Spark. It triggers computation to obtain the number of rows.
pdf.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 6 columns):
 #   Column          Non-Null Count  Dtype 
---  ------          --------------  ----- 
 0   transaction_id  4 non-null      int64 
 1   customer_id     4 non-null      int64 
 2   product         4 non-null      object
 3   quantity        4 non-null      int64 
 4   unit_price      4 non-null      int64 
 5   revenue         4 non-null      int64 
dtypes: int64(5), object(1)
memory usage: 324.0+ bytes
sdf.printSchema()
root
 |-- transaction_id: long (nullable = true)
 |-- customer_id: long (nullable = true)
 |-- product: string (nullable = true)
 |-- quantity: long (nullable = true)
 |-- unit_price: long (nullable = true)

4 Basic Data Analysis with PySpark

4.1 Selecting Columns

We often start by selecting the variables relevant to our analysis.

Pandas

pdf[
    ["product", "quantity", "unit_price"]
]
product quantity unit_price
0 Laptop 1 900
1 Phone 2 500
2 Mouse 3 20
3 Laptop 1 900

PySpark

sdf.select(
    "product",
    "quantity",
    "unit_price"
).show()
+-------+--------+----------+
|product|quantity|unit_price|
+-------+--------+----------+
| Laptop|       1|       900|
|  Phone|       2|       500|
|  Mouse|       3|        20|
| Laptop|       1|       900|
|  Phone|       1|       500|
+-------+--------+----------+

The select() operation in PySpark is similar to selecting columns in Pandas.

Filtering Rows

Suppose we only want transactions with a unit_price > 101.

  • Pandas
transaction_id customer_id product quantity unit_price revenue
0 1 101 Laptop 1 900 900
1 2 102 Phone 2 500 1000
3 4 103 Laptop 1 900 900
  • PySpark
from pyspark.sql.functions import col

sdf.filter(
    col("unit_price") > 101
).show()
+--------------+-----------+-------+--------+----------+
|transaction_id|customer_id|product|quantity|unit_price|
+--------------+-----------+-------+--------+----------+
|             1|        101| Laptop|       1|       900|
|             2|        102|  Phone|       2|       500|
|             4|        103| Laptop|       1|       900|
|             5|        102|  Phone|       1|       500|
+--------------+-----------+-------+--------+----------+

We can also use where() as an alternative to filter().

Creating New Variables

  • Calculate the revenue of each transaction: \[\text{Revenue} = \text{Quantity} \times \text{Unit Price}\]

Pandas

pdf["revenue"] = (
    pdf["quantity"] *
    pdf["unit_price"]
)
  • withColumn() creates a new column or replaces an existing one.

PySpark

from pyspark.sql.functions import col

sdf = sdf.withColumn(
    "revenue",
    col("quantity") * col("unit_price")
)

sdf.show()
+--------------+-----------+-------+--------+----------+-------+
|transaction_id|customer_id|product|quantity|unit_price|revenue|
+--------------+-----------+-------+--------+----------+-------+
|             1|        101| Laptop|       1|       900|    900|
|             2|        102|  Phone|       2|       500|   1000|
|             3|        101|  Mouse|       3|        20|     60|
|             4|        103| Laptop|       1|       900|    900|
|             5|        102|  Phone|       1|       500|    500|
+--------------+-----------+-------+--------+----------+-------+

Grouping and Aggregation

Business question: Which products generate the highest revenue?

Pandas

(
    pdf.groupby("product")
    ["revenue"]
    .sum()
    .sort_values(ascending=False)
)
product
Laptop    1800
Phone     1000
Mouse       60
Name: revenue, dtype: int64
  • The idea is the same as Pandas: group observations and calculate summary statistics. Spark distributes the partitions across workers.

PySpark

from pyspark.sql.functions import sum, avg, count

(
    sdf.groupBy("product")
    .agg(
        sum("revenue").alias("total_revenue"),
        avg("revenue").alias("average_revenue"),
        count("*").alias("transactions")
    )
    .orderBy(
        col("total_revenue").desc()
    )
    .show()
)
+-------+-------------+---------------+------------+
|product|total_revenue|average_revenue|transactions|
+-------+-------------+---------------+------------+
| Laptop|         1800|          900.0|           2|
|  Phone|         1500|          750.0|           2|
|  Mouse|           60|           60.0|           1|
+-------+-------------+---------------+------------+

Joining DataFrames

  • Suppose we have another dataset containing customer information.
Code
customers = [
    (101, "Alice", "France"),
    (102, "Bob", "Cambodia"),
    (103, "Charlie", "France")
]
customer_columns = [
    "customer_id", "customer_name", "country"
]
customer_pdf = pd.DataFrame(
    {
        "customer_id" : (101, 102, 103),
    "customer_name" : ("Alice", "Bob", "Charlie"),
    "country" : ("France", "Cambodia", "France")
    }
)
customer_sdf = spark.createDataFrame(
    customers,
    customer_columns
)
  • Pandas

Code
merged_pdf = pdf.merge(
    customer_pdf,
    on="customer_id",
    how="left"
)
merged_pdf.head(3)
transaction_id customer_id product quantity unit_price revenue customer_name country
0 1 101 Laptop 1 900 900 Alice France
1 2 102 Phone 2 500 1000 Bob Cambodia
2 3 101 Mouse 3 20 60 Alice France
  • PySpark

Code
merged_sdf = sdf.join(
    customer_sdf,
    on="customer_id",
    how="left"
)

merged_sdf.show(3)
+-----------+--------------+-------+--------+----------+-------+-------------+--------+
|customer_id|transaction_id|product|quantity|unit_price|revenue|customer_name| country|
+-----------+--------------+-------+--------+----------+-------+-------------+--------+
|        101|             1| Laptop|       1|       900|    900|        Alice|  France|
|        102|             2|  Phone|       2|       500|   1000|          Bob|Cambodia|
|        101|             3|  Mouse|       3|        20|     60|        Alice|  France|
+-----------+--------------+-------+--------+----------+-------+-------------+--------+
only showing top 3 rows

4.2 Using SQL with PySpark

  • Spark also allows us to write SQL queries directly.
  • First, register a DataFrame as a temporary SQL table.
sdf.createOrReplaceTempView("sales")
  • Then execute SQL:
result = spark.sql("""
    SELECT
        product,
        SUM(quantity * unit_price) AS total_revenue
    FROM sales
    GROUP BY product
    ORDER BY total_revenue DESC
""")

result.show()
+-------+-------------+
|product|total_revenue|
+-------+-------------+
| Laptop|         1800|
|  Phone|         1500|
|  Mouse|           60|
+-------+-------------+
  • Spark has optimizers that optimize the execution plan before running the query in SQL.

4.3 Understanding Lazy Evaluation

One important difference between Pandas and Spark is lazy evaluation.

Pandas

result = (
    pdf[pdf["quantity"] > 1]
    .groupby("product")
    ["unit_price"]
    .mean()
)

The computation is performed when the operation is executed.

PySpark

result = (
    sdf.filter(col("quantity") > 1)
    .groupBy("product")
    .avg("unit_price")
)

Spark builds an execution plan. Computation is triggered by an action.

  • Transformations define what we want to do: select(), filter(), withColumn(), groupBy(), join()…
  • Actions trigger computation: show(), count(), collect(), write()…

Why Is Lazy Evaluation Useful?

Spark can optimize a sequence of transformations before executing it.

== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[product#2], functions=[sum(quantity#3L)])
   +- Exchange hashpartitioning(product#2, 200), ENSURE_REQUIREMENTS, [plan_id=321]
      +- HashAggregate(keys=[product#2], functions=[partial_sum(quantity#3L)])
         +- Project [product#2, quantity#3L]
            +- Filter (isnotnull(quantity#3L) AND (quantity#3L > 1))
               +- Scan ExistingRDD[transaction_id#0L,customer_id#1L,product#2,quantity#3L,unit_price#4L]

  • explain() displays the execution plan. It helps us understand how Spark intends to process the data.
  • Key idea: Spark does not necessarily execute every operation immediately. It can optimize the overall computation plan before running it.

Saving Results

Pandas

pdf.to_csv(
    "output_pd.csv",
    index=False
)

PySpark

result.write \
    .mode("overwrite") \
    .option("header", True) \
    .csv("output_folder_spark")
  • Important: Spark generally writes output to a directory containing one or more part files, rather than creating one CSV file directly.

4.4 A Complete PySpark Workflow

  • Let’s combine the operations into one analysis.
  • Objective: Find the top products by total revenue.
from pyspark.sql.functions import col, sum, desc
sales_analysis = (
    sdf.withColumn(
        "revenue",
        col("quantity") * col("unit_price")
    )
    .groupBy("product")
    .agg(
        sum("revenue").alias("total_revenue")
    ).orderBy(
        desc("total_revenue")
    )
)
sales_analysis.show()
+-------+-------------+
|product|total_revenue|
+-------+-------------+
| Laptop|         1800|
|  Phone|         1500|
|  Mouse|           60|
+-------+-------------+
  • This is a typical data analysis pipeline:

Load → Transform → Aggregate → Sort → Save.

5 Introduction to Dask

5.1 What Is Dask?

  • Dask is a Python library for parallel and distributed computing.
  • It provides interfaces similar to familiar Python libraries.
  • Dask DataFrame is designed for working with larger-than-memory tabular datasets.
  • It can execute computations in parallel on a local machine or across a cluster.
  • Intuition: Dask aims to make parallel computing more accessible to Python users, particularly those already familiar with including Pandas, NumPy, Scikit-learn…

5.2 Dask DataFrame

  • Install Dask:
pip install "dask[dataframe]"
  • Load the data:

  • Notice the similarity with Pandas:

pdf = pd.read_csv("sales.csv")
ddf = dd.read_csv("sales.csv")
  • The interface is familiar, but Dask can partition the data and process partitions in parallel.
  • Each paralle partition is processed using built-in Python frameworks like NumPy, Pandas, Scikit-learn, etc.
  • It’s often known as general-purpose parallel computing framework for Python.

Pandas vs Dask

Question: Calculate the total revenue by product.

Pandas

pdf["revenue"] = (
    pdf["quantity"] *
    pdf["unit_price"]
)

result = (
    pdf.groupby("product")["revenue"]
    .sum()
)

Dask

ddf["revenue"] = (
    ddf["quantity"] *
    ddf["unit_price"]
)

result = (
    ddf.groupby("product")["revenue"]
    .sum()
    .compute()
)
  • .compute() triggers the computation and returns the result. It’s also perform lazy execution.

Understanding the Difference

Concept Pandas Dask PySpark
DataFrame Local Partitioned Distributed
Execution Eager Lazy Lazy
Parallelism Limited Yes Yes
Main interface Python Pandas-like SQL/DataFrame
Typical use Small/medium data Parallel Python workflows Large-scale distributed analytics
  • Dask is not simply a replacement for Pandas or Spark. The appropriate framework depends on the dataset, available infrastructure, and type of computation…

6 Summary and Discussion

6.1 Summary

  • Big Data becomes important when data volume, velocity, or variety creates challenges for traditional processing.
  • Distributed computing divides data into partitions and processes them in parallel.
  • PySpark provides a DataFrame and SQL interface for large-scale distributed data processing.
  • Dask brings parallel and distributed computing to the Python ecosystem with familiar interfaces.
  • The fundamental operations remain familiar: select, filter, transform, group, aggregate, and join.

Which Framework Should We Use?

Situation Suggested tool
Small dataset fitting comfortably in memory Pandas
Local parallel computing with Python Dask
Large-scale distributed data processing PySpark
SQL-based distributed analytics PySpark
  • Remark: Spark and Dask can also run locally.
  • Using them does not automatically make a small computation faster. Their benefits become more relevant when data size and computational requirements justify their overhead.

Final Takeaway

  • The goal of Big Data technology is not to change how we think about data analysis.
  • It is to allow familiar analytical operations to work at a much larger scale.
  • Choosing the right framework would allow smooth and efficient data analysis at scale.

🥳 Yeahhhh 🥂!!!










Let’s take a break!