PySpark for Data Science: Distributed DataFrames & Spark SQL

PySpark is the enterprise gold standard for big data science. In this class, we write distributed data transformations, register temporary SQL views, and run analytical queries across multi-terabyte datasets.

Hands-On PySpark: Distributed DataFrames & Spark SQL

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

# Initialize local multi-threaded SparkSession
spark = SparkSession.builder \
    .appName("VeewomDataScienceBigData") \
    .config("spark.driver.memory", "4g") \
    .getOrCreate()

# Create sample distributed DataFrame
data = [
    ("Alice", "Engineering", 125000, "US"),
    ("Bob", "Marketing", 85000, "UK"),
    ("Charlie", "Engineering", 140000, "US"),
    ("David", "Sales", 92000, "CA"),
    ("Eva", "Engineering", 160000, "CA"),
    ("Frank", "Marketing", 91000, "US")
]
columns = ["employee_name", "department", "salary", "country"]
df = spark.createDataFrame(data, columns)

# 1. High-Performance PySpark DataFrame Transformations
df_summary = (
    df
    .filter(F.col("salary") > 90000)
    .groupBy("department")
    .agg(
        F.count("employee_name").alias("headcount"),
        F.round(F.avg("salary"), 2).alias("avg_salary"),
        F.max("salary").alias("max_salary")
    )
    .sort("avg_salary", ascending=False)
)
df_summary.show()

# 2. Native Spark SQL Query Execution
df.createOrReplaceTempView("employees")
sql_result = spark.sql("""
    SELECT 
        country,
        department,
        COUNT(*) AS total_staff,
        ROUND(AVG(salary), 2) AS dept_avg
    FROM employees
    GROUP BY country, department
    ORDER BY country, dept_avg DESC
""")
sql_result.show()

# 3. Distributed Window Functions in PySpark
from pyspark.sql.window import Window

dept_window = Window.partitionBy("department").orderBy(F.col("salary").desc())
df_ranked = df.withColumn("dept_salary_rank", F.dense_rank().over(dept_window))
df_ranked.show()

# 4. High-Speed Broadcast Hash Join
departments_meta = spark.createDataFrame([
    ("Engineering", "Building 4", "Tech"),
    ("Marketing", "Building 1", "Growth"),
    ("Sales", "Building 2", "Revenue")
], ["department", "location", "division"])

# Broadcast small lookup table to avoid expensive cluster shuffle
df_joined = df.join(F.broadcast(departments_meta), on="department", how="inner")
df_joined.show()

PySpark MLlib Machine Learning Pipeline

When training models on 500 million rows, standard Scikit-Learn will run out of memory. Spark MLlib distributes feature vectorization and gradient calculations across the entire worker cluster:

from pyspark.ml.feature import VectorAssembler, StandardScaler
from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline

# Assemble features into a single distributed vector column
assembler = VectorAssembler(inputCols=["salary"], outputCol="raw_features")
scaler = StandardScaler(inputCol="raw_features", outputCol="features")
lr = LogisticRegression(featuresCol="features", labelCol="label", maxIter=20)

pipeline = Pipeline(stages=[assembler, scaler, lr])
# model = pipeline.fit(training_df)

Partitioning Best Practices

When writing out large datasets with PySpark, always partition by low-cardinality temporal or geographical columns: df.write.partitionBy("year", "month").parquet("s3://my-lake/orders/"). This ensures downstream queries perform fast partition pruning.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is PySpark?

PySpark is the Python API for Apache Spark. It allows data scientists to write clean, Pythonic code that executes across distributed multi-node clusters using Spark's high-speed JVM core.

Q2. What is a Broadcast Join in PySpark?

When joining a massive 100M-row DataFrame with a small 1,000-row lookup table, a standard shuffle join sends data across network cables. A Broadcast Join sends a full copy of the small table to every worker node, eliminating network shuffle overhead completely.

Q3. Why are Python UDFs slower in PySpark and what is the alternative?

Standard Python UDFs require expensive serialization of data between the JVM and Python interpreter processes. Modern PySpark uses Pandas UDFs (Vectorized UDFs) powered by Apache Arrow, which process whole batches at native C speeds.

Q4. How does Spark SQL register temporary views?

Calling df.createOrReplaceTempView('orders') registers a distributed DataFrame as an in-memory SQL table, allowing you to write standard ANSI SQL queries that run distributed across the cluster.

Q5. What is the role of Spark MLlib?

Spark MLlib is Apache Spark's distributed machine learning library, offering scalable implementations of regression, classification, clustering, PCA, and feature transformers designed to train on billions of records.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Big Data Architecture & Spark

Learn the cluster manager, driver node, and executor architecture.

Pandas DataFrames Manipulation

Translate single-node Pandas code into scalable PySpark DataFrames.

Cloud Data Warehouses: BigQuery & Snowflake

Connect PySpark to cloud data lakehouses for distributed analytics.

Dockerizing Data Pipelines & CI/CD

Package PySpark batch transformation scripts inside Docker containers.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!